In previous Drawing tool story series I have discussed about how to draw a simple line from c# code. Previous article can be found here http://munnaondotnet.blogspot.com/2011/11/drawing-tool-story-drawing-simple-line.html. In this short post we are going to take a look at how we can design theme based WPF application. The idea is pretty much same like asp.net theme switch.
Defining the theme
Changing theme is pretty simple we have do define the themes in a folder in our project and then change the themes in runtime by applying resource clear and merge. Bellow I have share a screen shot of solution explorer where its clearly seen that I have two theme in my project “Blend” and “Windows7” these are just names main styling is done in the Theme.xaml file.
Always use dynamic resource for themed application
For each instance of UI element that we want to style we can either add style or perhaps apply default look in the Theme.xaml so that it affect whole application. Bellow I have given a window xaml where its shown Lots of window element’s style is set to dynamic resource. This is the main trick of a themed application, if we apply static resource this would require a direct reference of the style, where as in dynamic reference we don’t need it, the style may or may not be defined.
In case of dynamic resource style binding If any style is been defined with the style name that will be applied other wise if any default style is been found that would be applied.
Change the theme
Last and most important part is switching the theme. Note that in above xaml I have added Two button and those are bind to command. In that command the main trick happens. Bellow the c# code is given.
Here I have changed the theme depending on what button is been pressed. First I have created a url for the theme directory and then clear existing resource the finally apply the new resource. That’s it theme is ready to switch dynamically with the single click on the window button.
Result in blend theme
result in windows7 theme
In this short article we have seen the basic idea behind themed application.