In my previous post Styles in Xamarin Forms I demonstrated creating a simple styles using XAML Style objects. However, as of version 3.0 of Xamarin Forms, you can also use CSS (Cascading Style Sheet) files/syntax to define your styles.
XAML Style is quite a verbose way of defining styles but if you’re used to WPF or UWP it’s probably something you’re quite happy with. If, however, you come from a web background you’ll probably be used to CSS files instead. Now you can use similar syntax to define your styles for Xamarin Forms (3.0 or above).
If you create a standard mobile application in Visual Studio you’ll get a simple ContentPage based application – as per the previous post we’re going to start off by simply defining a Lime green background for our ContentPage’s.
Now simply add a CSS file (mine’s named Styles.css) to your solution and set it’s Build Action to Embedded resource and place the following into the file
^ContentPage { background-color: Lime; }
Note: the CSS is case insensitive, but I’ve stuck to using the case associated with the controls/page here.
Notice the use of the ^ followed by the base type. If you read my previous post Styles in Xamarin Forms, you’ll notice that this is equivalent to an implicit style. i.e. it’s applied to anything of the type ContentPage.
To use this style we need to add the following to our ContentPage XAML
<ContentPage.Resources> <StyleSheet Source="Styles.css" /> </ContentPage.Resources>
Note: you do NOT need to add any namespace to use the StyleSheet (or at least I didn’t at the time of writing). if Visual Studio or Resharper suggests you need to add a namespace, just ignore it.
Now if you run your application you’ll be presented with the Lime background ContentPage.
If you’re used to CSS you’ll know that you can also declare an id (the equivalent of an explicit style) to your CSS. Let’s change our CSS to this following
#ContentStyle { background-color: Lime; }
Now we can assign this to either the StyleId or it will fallback to using x:Name (if no StyleId is set) on our control. For example
StyleId="ContentStyle"
or if you prefer you can simply use the x:Name (remember no StyleId should exist)
x:Name="ContentStyle"
We can also declare our CSS using CLASS selectors such as
.ContentStyle { background-color: Lime; }
Now we would use the StyleClass attribute on our ContentPage instead of StyleId or x:Name, i.e.
StyleClass="ContentStyle"
Finally, we can also declare CSS for child elements, so for example CSS for the Label which is a child of a StackLayout would look like this
StackLayout Label { background-color: Lime; }
See Selector reference for more on selector syntax, which also demonstrated setting style for direct child objects etc.
References
Styling Xamarin.Forms apps using Cascading Style Sheets (CSS)
Styling Xamarin.Forms Apps with CSS