How to detect the dark or light theme in Windows Phone 7

If the user of the Windows Phone 7 device switches from the default dark theme to the light theme, how do you detect which one is in use?

In the MSDN article Theme Resources for Windows Phone, there are two interesting resource keys that you can query. These are the PhoneDarkThemeVisibility and PhoneLightThemeVisibility keys. So based on these we can determine if we should use a dark or light background image in our application, like so:

var isLightTheme = (Visibility)Application.Current.Resources["PhoneLightThemeVisibility"];
var imageBrush = new ImageBrush();
var imageUri = new Uri(isLightTheme == Visibility.Visible ? "background-light.jpg" : "background-dark.jpg", UriKind.Relative);
imageBrush.ImageSource = new System.Windows.Media.Imaging.BitmapImage(imageUri);
MainPanorama.Background = imageBrush;
This post is licensed under CC BY 4.0 by the author.