Monday, 22 July 2013

Detecting Current Theme in Windows Phone - Dark or Light

If you stick to the default themes and brushes in windows phone apps, windows phone would adjust the styles according to the user's selection of dark and light theme settings.
But in cases where your app needs to set custom styles for UI elements, you would want to change styles according to the phone's current theme (Dark or Light).
To accomplish this the technique we use is to rely on some of the system default brushes. Once the system theme changes from Dark to Light and vice versa, the color these system brushes refer to changes automatically. In this example we use the PhoneBackgroundBrush. So when the current theme is Dark, PhoneBackgroundBrush's color is black and when the theme is switched to Light, the brush's color automatically change to White.
Code:
SolidColorBrush bgBrush = Application.Current.Resources["PhoneBackgroundBrush"] as SolidColorBrush;
if (bgBrush.Color == Color.White)
{
// current phone theme is Light
}
else
{
// current phone theme is Dark
}
An alternate approach is as below:
var visibility = (Visibility)Resources["PhoneLightThemeVisibility"];
if(visibility == Visibility.Visible)
{
// current phone theme is Light
}
else
{
// current phone theme is Dark
}
Both approaches work well and currently, there is no other straight forward/cleaner api exposed by windows phone for the functionality.

No comments:

Post a Comment