Simplifying your MAUI Styles with StyleClass

Styles classes enables you to have multiple styles applied to a control, in simple words it allows you to apply the concept of multiple inheritance to your styles.

It gives you the flexibility to avoid creating a lot of styles that will be inherited from.

How we usually do it? 

Imagine the scenario were we want to create an AppTheme for our app, and we have a design that handles all the Labels with 2 sizes, Small and Medium, for that case we usually start by doing something like this:

Now, let’s imagine we need to add more elements to our styles, a Bold Label (That needs to be Medium), and another Bold Label (That needs to be Small).

For that we usually use BaseResourceKey, and we create new styles that extends from the original one.

To use it, we just assign the specific styles that we need:


How we can simplified it?

Let’s start by creating or two base styles, Small, Medium.

As you see instead of creating it with x:Key, we are using the Class attribute.

Now we will create the other styles, but instead of inheriting from the base ones, we will create independent styles.

To use it:

That’s it, now we have a beautiful AppTheme class with less code.

If you want to learn more about it, you can check the official documentation here.

Happy coding! 🙂

You may also like