Inheritance in XAML Styles


Style inheritance in XAML? Sounds funny? No. If we have inheritance in classes, CSS styles; then why not in XAML styles? There are many such occasions when we need to copy the same style in multiple templates/styles of a control.

 

In this post, we will learn how to use a single piece of style and use it in other place to inherit the common styling. If you are using XAMLs excessively, this might be a very good topic for you.

 

If you are a XAML designer and/or building a lot of controls in XAML, you might have used the common styles in all the control templates in order to provide the similar look & feel across your controls. In OOPs concept we already learnt about inheritance and if you worked on CSS styles, you might have done that too. In XAML also, we can use the same thing to declare a base style and use it in all places where we need it.

 

It’s not a new thing but I have observed that, many people are unaware of this. Hence, thought to share this trick with you in case if you don’t know or forget about it, this post will help you next time when you need inheritance in your XAML.

 

To implement this, just create a base style with a Key name and a proper TargetType. Make sure to set both of them properly. Then list down all the common property values using <Setter/> tag as shown in the first code snippet below:

 

XAML Style Inheritance

 

Now when you want to use that base style in a different style (of same TargetType), just call the inheritance by setting the base style using BasedOn attribute. The value of it should be the Key name as a StaticResource as shown in the second code snippet above (highlighted).

 

That’s it! All the common styles will now inherit to the derived style and you are good to go without copying the same thing again and again. Multiple and Multilevel inheritance are supported in XAML styles. So, keep on using them. Cheers.

 

In case you have any specific questions related to this topic, drop a line below and I will try to answer you as soon as possible. Also, I am available on Twitter and Facebook. Connect with me there to get my updates. Don’t forget to ask your queries.


If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Twitter , Facebook , Google+ and LinkedIn . I would love to hear your thoughts and opinions on my articles directly. Also, don't forget to share your views and/or feedback in the comment section below.

2 comments

  1. Why it must sound funny? Perhaps for stupid Hindi "developers" it may sound funny.

    ReplyDelete
    Replies
    1. "Anonymous" dont you think you are idiot? Thanks for sharing this article with us.

      Delete


 
© 2008-2016 Kunal-Chowdhury.com - Microsoft Technology Blog for developers and consumers | Designed by Kunal Chowdhury
Back to top