Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

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.


advertisement

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:

button1.SetResourceReference( 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. button1.SetResourceReference(Control.TemplateProperty, "RoundButtonWithThickEdge"); button2.SetResourceReference(Control.TemplateProperty, "RoundGelButton"); button3.SetResourceReference(Control.TemplateProperty, "Flattish");

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."
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date