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"
        <ResourceDictionary Source="BureauBlack.xaml"></ResourceDictionary>
Without style 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

            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
                //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.

C# Reactive Extensions - Buffer and Window

I was going through Buffer and Window in RX, thought a few examples would help clear the differences. First create a buffer of even numbe...