3
votes

I'm adding some controls dynamically in my Windows Phone 8.1 application. In the XAML, you can set various styles to the current theme's style just as I set the foreground attribute of this TextBlock control in the following example.

<TextBlock Text="Hello World" Foreground="{ThemeResource PhoneAccentBrush}" />

I want to be able to do the same thing in the code behind, but have not yet been able to determine how to do this. I create the TextBlock programmatically as follows.

TextBlock textBlock = new TextBlock() {
    Text = "Hello World",
    Foreground = // Need to get phone accent brush from theme
};

I've seen examples where different theme values are stored as follows, but this Dictionary doesn't seem to contain any keys when I checked for theme resources.

SolidColorBrush phoneAccent = new SolidColorBrush((Color)Application.Current.Resources["PhoneAccentColor"]);

Any help would be appreciated. Thank you!

2
Does Rob's answer work when you change the theme during run-time? - DK.
Yes, it does work when the theme changes during run-time. - tribute2ro
Thanks @tribute2ro, that's an interesting thing to know. I mostly work with Windows applications, so if one-time brush assignment in the code works the same as ThemeResource binding in XAML, there must be a significant difference in themes handling between Win 8.1 and WP 8.1. - DK.

2 Answers

2
votes

Load it from PhoneAccentBrush not PhoneAccentColor:

Brush accentBrush = Resources["PhoneAccentBrush"] as Brush;
TextBlock textBlock = new TextBlock()
{
    Text = "Hello World",
    Foreground = accentBrush 
};
0
votes

In Visual Basic .net:

.Foreground = CType(Resources.Item("PhoneAccentBrush"), Brush)