UI, Xamarin

Inheriting styles in Xamarin Forms

When designing an application it’s common and also an excellent practice to work with styles, especially when we have controls with the same visual characteristics. But we also encounter scenarios where two or more controls which will need different styles but with most of the visual properties exactly the same, so what do we normally do in these cases? … ? Would we create as many styles as necessary?, taking into consideration that many of these controls have visual properties that are equal to other controls, that would make our code more extensive and repetitive … ?‍♀

But the good news is that we can inherit the styles that contain the properties that we need to reuse. ?


First of all… There are some important things that we need to know

➖To understand this topic correctly it’s important to be clear in what a Style is. If you don’t know about it, you can read  this article.

A style can only inherit from styles at the same level, or above, in the view hierarchy.  ✍

This image has an empty alt attribute; its file name is Screen-Shot-2020-03-15-at-4.39.37-PM-1024x305.png


Let’s start!

To implement inheritance in styles you just have to use the BasedOn property on the new style we created. This is achieved by setting the BasedOn property to a StaticResource markup extension that references a previously created Style.

Let’s see an example!

Step 1⃣: Create a style with a normal structure.

Step 2⃣: Create other style but in this case adding the BasedOn property, since this is the property that is responsible of the style inheritance. Here you must add the name of the desired style as follows:

This image has an empty alt attribute; its file name is BaseonStrc-1024x115.png

Step 3⃣: And finally add the style to your controls!

And Done!  ?

This image has an empty alt attribute; its file name is StyleResult.png

Advantages ✍

? Your code will be cleaner and more organized

? You’ll save time writing code

? You will not have styles with such repetitive visual properties


Thanks for reading !!! ?

Spanish post: https://medium.com/@reyes.leomaris/heredando-estilos-en-xamarin-forms-3ae3e25d0aaa?sk=1b27b8d03984e280a77c9107d5dafdff

References: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/styles/xaml/inheritance

Tagged ,

1 thought on “Inheriting styles in Xamarin Forms

Leave a Reply

Your email address will not be published. Required fields are marked *