Follow us on X (Twitter)  Like us on Facebook  Connect with us on LinkedIn  Subscribe to our YouTube Channel  Subscribe to our WhatsApp Group

Inheritance in XAML Styles


Do you know that we can inherit a base XAML style to another XAML style to copy the same set of styles? In this post, we are going to discuss on this. - Article authored by Kunal Chowdhury on .

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.

Have a question? Or, a comment? Let's Discuss it below...

Thank you for visiting our website!

We value your engagement and would love to hear your thoughts. Don't forget to leave a comment below to share your feedback, opinions, or questions.

We believe in fostering an interactive and inclusive community, and your comments play a crucial role in creating that environment.