Customizing App.xaml.cs
Windows Phone devices allow users two theme options, either dark or light.
In the WP7 beta dev tools, however, there no straight-forward way for Windows Phone Silverlight developers to find out what the current theme is, though there is a hack. The developer must interrogate the app resources to find the color of the PhoneBackGroundColor. Under the dark theme it is black, while under the light theme it is white.
The following code can be thrown into App.xaml.cs to add a little elegance to this hack.
First, a brief enum is needed. It can be added in App.xaml.cs above the App class, or simply placed in its own cs file in the project:
public enum Theme{Light,Dark}
A CurrentTheme property is added to the App class:
private static Theme _currentTheme; public static Theme CurrentTheme { get { return _currentTheme; } private set { _currentTheme = value; } }
And then we assign a value to CurrentTheme in the App class constructor by interrogating Resources:
public App() { var bgc = Resources["PhoneBackgroundColor"].ToString(); if (bgc == "#FF000000") CurrentTheme = Theme.Dark; else CurrentTheme = Theme.Light; //etc.
The CurrentTheme is now retrievable from anywhere in the application like so:
switch(App.CurrentTheme) { case Theme.Dark: MessageBox.Show("Dark"); break; case Theme.Light: MessageBox.Show("Light"); break; }
Moreover, if a user presses the Windows button at lower center on a device and resets the theme, the new theme will be assigned to CurrentTheme when the application returns from tombstoning.
There is a rumor that in the RTM of the WP7 dev tools, two new properties will be available for picking up the current theme: DarkThemeVisibility and LightThemeVisibility.
For ease of migration to the RTM, you can add the following two properties to App.xaml.cs for now as placeholders – you should be able to simply switch them out later should the new methods become available:
public static bool DarkThemeVisibility { get { return CurrentTheme == Theme.Dark; } } public static bool LightThemeVisibility { get { return CurrentTheme == Theme.Light; } }