WPF: Adventures in Theming (Part 1)

I just finished doing a ton of styling/theming work in WPF, after doing so I had many thoughts and experiences on the subject that I thought I would share. So I decided to throw together a multipart series of posts on the things I ran across and maybe some tricks.

I suppose I should start off with the hello world of WPF theming. In your application dictionary you’ll simply merge another resource dictionary containing many implicit control styles which will look like this in XAML.

Although, in my case I actually had to do it in code because we don’t have a centralized application project. All of that information is stored in another assembly that contains our reusable UI controls as well as all the implicit styles we use to theme our application. So to do basically the same thing in code, you can just do something like this (If you want to just replace the application dictionary),

So what exactly are implicit styles and how do I add them to the application resource dictionary? An implicit style is simply a style with a resource key matching the type of the control it will act as the style for. To show you a full example of an implicit style, here is the style for a label straight out of Blend.

You could place that style in your Application’s resource dictionary, change the foreground to Red and automatically restyle every unstyled label in your application to match it.

If in some other location in your application you have a label using a custom style you can still take advantage of this style but you’ll have to do a little bit of work. We need to tell WPF that it needs to lookup a base style to merge into any custom style. We can do that by putting,

BasedOn="{StaticResource {x:Type Label}}"

on a custom label style. This will cause WPF to merge in the label style you defined in your application resource dictionary into a custom label style.