Setting image source programmatically depending on the current phone theme

Every Windows Phone 7 application needs to support both dark and light themes, so it is sometimes needed to change the image displayed depending on the current phone theme. At the moment, there is only one way to find out the theme that is currently being used and it is achieved by examining the PhoneLightThemeVisibility resource. Its not the most clever way to go, but its all we have for now.

Visibility v = (Visibility)Resources[“PhoneLightThemeVisibility”];
String url = v==Visibility.Visible?
“/MYAPP;component/Icons/Light/checkWithCircle.png” : “/MYAPP;component/Icons/Dark/checkWithCircle.png”;

Uri imgURI = new Uri(url, UriKind.Relative);
UniversalImage.Source = new BitmapImage(imgURI);

Hope it helps!

P.S. if you are trying to access Resources from something other that UIElement (e.g. from the ViewModel class), you could use Application.Current.Resources to get the PhoneLightThemeVisibility resource.

Convert WPF visuals to Windows metafile (WMF)

There’s already a solution for this, you can convert both visual or UIElemnt to metafile… the only (and the biggest) drawback is that the metafile that you get is not a vector because you are pasting a bmp inside it… here are the links:

http://www.switchonthecode.com/tutorials/wpf-tutorial-getting-from-wpf-to-a-metafile-and-onto-the-clipboard

and the visuals addon taken from the microsoft forums:

private static BitmapSource CaptureScreen(Visual target, double dpiX, double dpiY)
{
if (target == null)
{
return null;
} Rect bounds = VisualTreeHelper.GetDescendantBounds(target); RenderTargetBitmap rtb = new RenderTargetBitmap((int)(bounds.Width * dpiX / 96.0),
(int)(bounds.Height * dpiY / 96.0),
dpiX,
dpiY,
PixelFormats.Pbgra32); DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(target);
ctx.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
} rtb.Render(dv); return rtb;
}

EDIT: if your visual/UIElement has transparent background, the code supplied above will make an image with black background… the workaround is to use the PngBitmapEncoder instead of BmpBitmapEncoder