Tuesday, 26 June 2012

WPF: Selecting a style at runtime

Recently I got hold of around 6 styles and needed to try them to see which one fits perfectly in our application. We can either change the <Application.Resources>, add a <ResourceDictionary> to set the style or we could do it dynamically to see the results.

Where to get the styles from?

There are few style available on web. One is at http://wpfthemes.codeplex.com/
Or create your own using http://thematic.codeplex.com/

Using it in Application.Resources:

-> First we add the XAML file containing the style to the project.
We add the file “BureauBlack.xaml” to the project

-> In App.xaml of application we write:
<Application x:Class="StyleSelector.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary Source="BureauBlack.xaml"></ResourceDictionary>
    </Application.Resources>
</Application>
Results:
Without style image   
With:

 image  

(there is some problem with the Style, it doesn't set the Window background color)

Setting style in code

Now let's try to set the style of a window in code. Here is a method which takes in a XAML file name (containing styles and added to project). We create a new ResourceDictionary object and set it to the Window's Resource collection.
        private void SetStyle(string xamlFileName)
        {
            //clear the resources
            this.Resources.Clear();

            if (!string.IsNullOrEmpty(xamlFileName))
            {
                //load new resources
                ResourceDictionary resDict = new ResourceDictionary();
                resDict.Source = new Uri(xamlFileName, UriKind.Relative);

                //merge the resources to preserve any other resource you may have added
                this.Resources.MergedDictionaries.Add(resDict);
  
                //or to overwrite and avoid memory leak you could also do this
                //this.Resources = resDict;
             }
        }        


We can use this method in the "Set Style to:" Combo Box selection changed event.
 

No comments:

Post a Comment

Note: only a member of this blog may post a comment.

Shorts - week 3, 2022

Post with links to what I am reading: 1. A very good post on different aspects of system architecture: https://lethain.com/introduction-to-a...