Google Xamarin.Forms 3.0: Styling apps using Cascading Style Sheets for beginners tutorial (C# - Xaml) | SubramanyamRaju Xamarin & Windows App Dev Tutorials

Saturday 19 May 2018

Xamarin.Forms 3.0: Styling apps using Cascading Style Sheets for beginners tutorial (C# - Xaml)

Introduction:
You may heard that Xamarin.Forms 3.0 introduces the ability to style an app using Cascading Style Sheets (CSS). We can create a style sheet that consists of a list of rules, with each rule consisting of one or more selectors and a declaration block. A declaration block consists of a list of declarations in braces, with each declaration consisting of a property, a colon, and a value. When there are multiple declarations in a block, a semi-colon is inserted as a separator.



Requirements:
  • This article source code is prepared by using Visual Studio Community for Mac (7.4). And it is better to install latest visual studio updates from here.
  • This sample project is Xamarin.Forms PCL project and tested in Android emulator and iOS simulators.
  • Used Xamarin.Forms version is 3.0.0 and we can also use later version.
Description:
This article can explain you below topics:
1. How to create Xamarin.Forms PCL project with Visual Studio for Mac?
2. How to create CSS styles in Xamarin.Forms?
3. How to use CSS styles in Xamarin.Forms?

1. How to create Xamarin.Forms PCL project with Visual studio for Mac?
First we need to create the new Xamarin.Forms project. 
  • Launch Visual Studio for Mac.
  • On the File menu, select New Solution.
  • The New Project dialog appears. In the left pane Multiplatform App Xamarin.Forms > Blank Forms App and click on Next.
  • Enter your App Name (Ex: FormsXamlCSS). Select Target Platforms to Android & iOS and Shared Code to Portable Class Library  after that click on Next button.
  • You can choose your project location like below and Create new project.

And project structure will be.
  • FormsXamlCSS: It is for PCL shared code.
  • FormsXamlCSS.Droid: It is for Android.
  • FormsXamlCSS.iOS: It is for iOS.
2. How to create CSS styles in Xamarin.Forms?
Right click on your PCL project => Add => New Folder and name it "Assets". After that we need to create styles file by right click on "Assets" folder => Web => Empty CSS File and name it styles.css like below
Note: Make sure your CSS file should have a Build Action to EmbeddedResource else it will fail to load. 
After that add below styles to CSS.
styles.css:
  1. ^contentpage {  
  2.     background-colorwhite  
  3. }  
  4.   
  5. stacklayout {  
  6.     margin20;  
  7.     background-color: lightgray;  
  8.   
  9. }  
  10.   
  11. .detailPageTitle {  
  12.     font-stylebold;  
  13.     font-size35;  
  14.     margin-left10;  
  15. }  
  16.   
  17. .detailPageSubtitle {  
  18.     text-aligncenter;  
  19.     font-styleitalic;  
  20.     font-sizemedium;  
  21.   
  22. }  


In above file, we added different rules for selectors with different properties.
  • Set the background color to white for ContentPage.
  • Set the margin value to 20 and background color to LightGray for StackLayout.
  • Page Title should have a bolded text with font size 35 and margin left to 10 px.
  • Page SubTitle should be center align with italic format and medium font size.

3. How to use CSS styles in Xamarin.Forms?
Now it is time to use our css styles file in the xaml pages. And we need to follow steps below:
Step 1: 
We need to use StyleSheet class which will help to load and parse a style sheet. So we can refer our styles sheet like below
Xaml:
  1. <ContentPage ...>  
  2.     <ContentPage.Resources>  
  3.         <StyleSheet Source="Assets/styles.css" />  
  4.     </ContentPage.Resources>  
  5.     ...  
  6. </ContentPage>  
Alternatively, the style sheet can be loaded and parsed with the StyleSheet class by inlining it in a CDATA section:
  1. <ContentPage ...>  
  2.     <ContentPage.Resources>  
  3.         <StyleSheet>  
  4.             <![CDATA[  
  5.             ^contentpage {  
  6.                 background-color: lightgray;  
  7.             }  
  8.             ]]>  
  9.         </StyleSheet>  
  10.     </ContentPage.Resources>  
  11.     ...  
  12. </ContentPage>  
C#
In C#, a style sheet can be loaded as an embedded resource and added to the ResourceDictionary for the page:
  1. using System.Reflection;  
  2. using Xamarin.Forms;  
  3. using Xamarin.Forms.StyleSheets;  
  4.   
  5. namespace FormsXamlCSS  
  6. {  
  7.     public partial class MainPage : ContentPage  
  8.     {  
  9.         public MainPage()  
  10.         {  
  11.             InitializeComponent();  
  12.   
  13.             this.Resources.Add(StyleSheet.FromAssemblyResource(  
  14.                 IntrospectionExtensions.GetTypeInfo(typeof(MainPage)).Assembly,  
  15.                 "FormsXamlCSS.Assets.styles.css"));  
  16.         }  
  17.     }  
  18. }  
Step 2:
Now we can apply the styles properties for your controls by referring CSS id's like below: 
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              x:Class="FormsXamlCSS.MainPage"  
  5.              Title="Monkey Details">  
  6.     <ContentPage.Resources>  
  7.         <StyleSheet Source="Assets/styles.css" />  
  8.     </ContentPage.Resources>  
  9.     <StackLayout>  
  10.             <Label Text="Page Title" StyleClass="detailPageTitle" />  
  11.             <Label Text="Page SubTitle" StyleClass="detailPageSubtitle"/>  
  12.      </StackLayout>  
  13. </ContentPage>  
Note: 
1. CSS uses selectors to determine which elements to target. Styles with matching selectors are applied consecutively, in definition order. Styles defined on a specific item are always applied last. So in our styles file (styles.css), we taken two selectors are ContentPage and StackLayout.
2. CSS uses properties to style a selected element. Each property has a set of possible values, and some properties can affect any type of element, while others apply to groups of elements.

Also make sure to your all three projects (PCL, Android and iOS) should have Xamarin.Forms Nuget package version should be 3.0 or later. Otherwise you will get xaml parsing exception for StyeleSheet like below:


To check your project current Xamarin.Forms version, right click on your project "Packages" folder.
Currently in above screen, current PCL project having X.F version 2.5.0. We need to Update it for version 3.0 or later like below:


Demo screens from Android:

Demo screens from iOS:

You can also directly work on below sample source code to understand this article. 

FormsCSSSample

Reference:
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/styles/

FeedBack Note: Please share your thoughts, what you think about this post, Is this post really helpful for you? I always welcome if you drop comments on this post and it would be impressive.

Follow me always at @Subramanyam_B
Have a nice day by  :)

2 comments:

  1. Error Resource 'Assets/styles.css' not found. (CSSXamarin)

    I am getting this error. My xamarin.forms version is 3.0 above Still i am facing this problem. please suggest

    ReplyDelete
    Replies
    1. Test with the path “/Assets/styles.css, or also make sure your styles.css Build Action to EmbeddedResource

      Delete

Search Engine Submission - AddMe