Styles Dictionary
Posted by Jamil Rzayev on December 5, 2008
Each time I build rich user window on WPF I think I have to write the same lines of code of style concept for each buttton or textbox. And the following question comes in mind: Why I don’t place all my styles in one XAML file to dynamically load them in future?
For example, if I have five buttons and each of them must have 40 in Width, 21 in Height, GradientColorBrush as BackgroundColor, WhiteSmoke color as Foreground and Margin equals to 5. I simply can write for each button the following lines of code:

It is easy to understand that writing for each cotrol separate style code will blow our XAML file and you as a developer willl have to spend much more time to cover all UI code in future.
WPF allows us to create special XAML file for filling it with styles and load them as we need.
Such type of file is named ResourceDictionary. It is basic XAML file with following header:

Then we write special lines of code for each style. using Style tag into that file between ResourceDictionary tags. For each important property which I want to assign a value I use Setter tag with Property and Value attributes.

That is all I need to do. For the moment I make some changes in window xaml code by using in each control declaration Style poperty and assign to it name of style. i only use Style tag and any additional attrubutes are deleted.
Style=“{DynamicResource ButtonStyle}”
At last to make it work correctly I put code to App.xaml file to load styles at application startup. I put file with styles in separate folder Styles.

That technique requires a bit more time to be accustomed with dictionaries but in everyday practice it reduces great time of development.
Topchiyev said
Hi Jamil.
It’s a nice note.
Thanks.
Also you can store some component templates directly in current xaml file.