Xamarin Forms & Custom CSS Properties

Do you ever plan to make your CSS properties? I will show you how 😋

As far as we could start using CSS in our Xamarin Forms application we stock with a problem that not all things we want are in. All-time count of supported properties is growing but not all the time it met our requirements. Or we create some controls and want to style some properties of it also from CSS like other controls.

How CSS in Xamarin Forms applies to controls?

At Xamarin.Forms.Core project you may find registration of all CSS properties for Xamarin Forms. All they are registered as an StylePropertyAttribute inside AssemblyInfo.cs file. At the initializing of Xamarin Forms static class Registrar start registration of attributes, also CSS attributes. His function RegisterAll call RegisterStylesheets which makes all registration works.

RegisterStylesheets by himself get allStylePropertyAttribute from Xamarin.Forms.Core assembly(added at AssemblyInfo.cs) and assign into Registrar.StyleProperties property, which takes CSS name as a dictionary key and list of StylePropertyAttribute as a value.

After registration, when any CSS file or inline CSS are applied(in Page, Control or App.xaml Dictionary) StyleSheet class start reading and parsing CSS with CssReader . If reading whole property succeed — it will add selector and style into style collection(Styles) into StyleSheet object that will be returned(same as for Xaml Styles).

Now during drawing elements on the screen VisualElement class comes to play. As you may know, Visual Element implements IStylable interface and provide realization of GetProperty method. There we try to get by key our Style, where key is the name of a CSS property.

Also good to mention that each property that has his interpretation in CSS are required to have a type converter.

What’s there with Style Property Attribute?

Right now this is private sealed class and you can’t create instance of it in your project. Even if new attributes will be frequently added to Xamarin Forms, it’s not solving a problem when we want to create a custom one.

A Pull Request at GitHub with opening Style Property Attribute or Adding easy possibility to register own CSS Properties, but it’s blocked by reviewers, hope it will change one day.

Your attention there may change something also 🙃

How to make CSS property now?

Reflection, reflection and one more time — reflection. Here is an example of implementation and how to register it:

Sources are taken from Open Source Magic Gradients — Xamarin Library based on SkiaSharp to draw enhanced gradients in light and fast way.

Thanks for reading, more is coming soon 🤯…

Microsoft MVP | C# .Net | Xamarin