Simple skinnable and Theme management in WPF user interface
A skinnable interface is the gotha of the user interface, the developer use standard control and set the behaviour, the designer skin it with some tool and creates a beautiful user interface. In WPF this is possible thanks to XAML and styles, but it is possible to simple include in an application a series of skin and load at runtime??. The answer is Yes, it is possible.
Let’s Start with a simple page with a combo and a textblock
|
|
The key part is that the resources are defined in an external resource file (A dictionary of resources), placed in Themes/Main.xaml, and the textblock simply declare that his Style is equal to a DynamicResource called StdText, that resource is in the external file, here is the full listing of Themes/Main.xaml
|
|
Nothing special, the style is empty :D, now look at the structure of the project
The project include some subfolder of the Themes directory, all these directory contains a file called Main.xaml, and in these files I store the style for the theme, here is an example of the Themes/Green/Main.xaml file
|
|
Ok this is nothing special, I simply set the font to green foreground and changes other properties. Thanks to the WPF concept of Style, I can change really every property of the text object. All these themes files are not included in the compilation, build action is set to none and I simply tells the compiler to copy to output directory if the file are changed. Now here is the code in the main program that scans Themes directory to find all subdirectories that contains a file called Main.xaml.
|
|
Well, a simple linq query permits me to scan all subdirectory of Themes, takes only the subdirectory that contain a Main.xaml File. All the result are stored in a simple class called ThemeData that contains the theme name (the name of the subdirectory) and the file name. Now here is the code to handle change of selection in the combobox, where I set the new theme
|
|
Really simple, I load the file in a stream, deserialize with XamlReader, and substitute to the original dictionary. Here is the result
The combo automatically enlists all subdirectories that contain a main.xaml file, if you change the theme
Et voilà , the theme is changed ;). If you like it, you can close visual studio, go to the debug directory and manually create another theme, run the program again without recompiling and the new theme is already active (because it is selected runtime). This permits a user to change the appearance of the program once the program is deployed.
Alk.