Wednesday, January 27, 2010

Making WPF applications display as on a particular operating system

WPF is great for styling. They even included different default styles for each Windows operating system so that the controls look "native". So making an application look as if native to the operating system is not a problem. But how can one do the opposite: force the application to always display as if on a specific operating system?

The solution is to include the default theme for that OS in the resources of your application, window, user control, etc, so one can even style different parts for different operating systems, if need be.

Well, this is how you can make you application use the Vista/Windows7 Aero interface. In you App.xaml add an Application.Resources block and a ResourceDictionary with the source /PresentationFramework.Aero, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml. If you have already a style in your application resources, add the resource dictionary in a ResourceDictionary.MergedDictionaries block. Like this:

<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="/PresentationFramework.Aero,
Version=3.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35,
ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml"
/>
<ResourceDictionary Source="/My.Namespace;component/Themes/MyApplication.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>


The operating system theme files that you can choose from are:
AssemblyTheme file
PresentationFramework.Aeroaero.normalcolor.xaml
PresentationFramework.Classicclassic.xaml
PresentationFramework.Lunaluna.homestead.xaml
PresentationFramework.Lunaluna.metallic.xaml
PresentationFramework.Lunaluna.normalcolor.xaml
PresentationFramework.Royaleroyale.normalcolor.xaml


Of course, the method of loading the theme might be through code, and so this can be used to programatically and dynamically change the theme:

protected override void OnStartup(StartupEventArgs e)
{
Uri themeUri = new Uri(myThemeUriString, UriKind.Relative);
ResourceDictionary theme = (ResourceDictionary)Application.LoadComponent(themeUri);
Resources.MergedDictionaries.Add(theme);
}
base.OnStartup(e);
}

0 comments: