by Wojciech Sura

Theme-aware resources in Windows Phone

Windows Phone supports two themes: light and dark. Since UI in this ecosystem is quite… say, minimalistic, the first theme can be described as “black on white” and the second as “white on black”.

The most common way to design appearance of your application is to use predefined resources, which are provided by the system. For instance, to create text in a frame with default theme colors, write:

[xml]<Border Margin="4" BorderBrush="{ThemeResource PhoneForegroundBrush}"
BorderThickness="{ThemeResource ButtonBorderThemeThickness}"
Background="{ThemeResource PhoneBackgroundBrush}">
<TextBlock Foreground="{ThemeResource PhoneForegroundBrush}"
FontSize="{ThemeResource TextStyleExtraLargePlusFontSize}">Themed manually</TextBlock>

The border will match current theme color:


But what if you want to introduce your own styles to application, but still match current theme?

The solution is to create different ResourceDictionary objects for light and dark scheme and then to import them in special way to your page:

<ResourceDictionary x:Key="Light" Source="Light.xaml" />
<ResourceDictionary x:Key="Dark" Source="Dark.xaml" />

The phone will now choose appropriate resource file, depending on current theme. Remember to use ThemeResource instead of StaticResource though, such that when theme changes all relevant values will be reloaded fromĀ appropriate ResourceDictionary.