RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Simplify Your XAML with Resources and Control Templates  : Page 3

Although it's tempting to style your WPF controls directly in their containing XAML files or through code, placing styling in control templates stored in external resource dictionaries offers a robust and reusable alternative.


Applying Styles in Code

What you've seen so far is only part of the story, because while the styles are now loaded into the RootGrid's resources using code, the style is still applied in the XAML. You can set styles through code as well by using the FrameworkElement's SetResourceReference method and applying the resource to the control's dependency property. Assigning the styles through code is often a useful alternative to setting up properties in XAML.

Basically, this statement in XAML…

<Button x:Name="button1"
  Template="{DynamicResource RoundButtonWithThickEdge}" />

…is equivalent to the code:

   Control.TemplateProperty, "RoundButtonWithThickEdge");
Figure 5. Programmatically Applied Styles: This version of the application programmatically applied styles stored in the dictionary file ButtonStyles.Xaml.

As an example, the following code applies styling to two of the remaining buttons:

//Set the template property in code 
// by using the Property and a Key.

Remove the previously set TemplateProperty for button1 applied in the XAML, and add the preceding code to style the remaining buttons. With that code in place, run the application again (see Figure 5). Note the round gel gradient style of Button 2 and the flattish style of Button 3.

As you can see, it's far more fun playing with XAML styles than applying oneself to serious learning, but for those who want to explore some more, here are some good links for learning how to use Expression Blend:

Srinath M. S. says: "I would love to leave a footprint in this flat world."
Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date