Skip to content

Getting Started By Code

David Rettenbacher edited this page Feb 22, 2019 · 2 revisions

Install

Go to NuGet and install the appropriate flavor of XamlCSS:

Initialize

Call Css.Initialize(...) in your startup code, before the first usage of stylesheets.
If you use the ResourceDictionary in App.xaml, you must place the Initialize(...) call before the InitializeComponent() call.

Depending on the platform Css can be

  • XamlCSS.XamarinForms.Css
  • XamlCSS.WPF.Css
  • XamlCSS.UWP.Css

XamarinForms

You have to specify the root element like the App or MainPage. If you want to use embedded (s)css files files, you must specify the assemblies containing the embedded resources.

Example without support for embedded (s)css files:
App.xaml.cs

public App()
{
    XamlCSS.XamarinForms.Css.Initialize(this);
    ...
}

Example with support for embedded (s)css files:
App.xaml.cs

public App()
{
    XamlCSS.XamarinForms.Css.Initialize(this, new[]{ typeof(TypeOfAssemblyContainingEmbeddedCssFiles).Assembly});
    ...
}

WPF

Requires no extra parameters to get embedded (s)css files.

Example with support for embedded (s)css files:
App.xaml.cs

public App()
{
    XamlCSS.WPF.Css.Initialize();
    ...
}

UWP

If you want to use embedded style files, you must specify the assemblies containing the embedded resources.

Example with support for embedded (s)css files:
App.xaml.cs

protected override void OnLaunched(LaunchActivatedEventArgs e)
{
    XamlCSS.UWP.Css.Initialize(new[]{ typeof(TypeOfAssemblyContainingEmbeddedCssFiles).Assembly});
    ...
}

Define Style with Css

Next define a css as a string. This string could be a string in your application class:

this.CssStyle = @"
.important
{
    BackgroundColor: Red;
    FontSize: 25;
    WidthRequest: 200;
}
Label
{
    TextColor: Red;
    FontSize: 25;
}
Button
{
    TextColor: Blue;
    BackgroundColor: Black;
}
";

Create and Apply Stylesheet

Parse the style string into a stylesheet and apply it to a root element (i.e. App, MainWindow,...):

var stylesheet = XamlCSS.CssParsing.CssParser.Parse(this.CssStyle);

Css.SetStyleSheet(this, stylesheet);

Example App-Class (Xamarin-Forms)

The whole class looks like this

using Xamarin.Forms;
using XamlCSS.XamarinForms;

namespace CssApp
{
    public partial class App : Application
    {
        public App()
        {
            Css.Initialize(this);

            InitializeComponent();

            var stylesheet = XamlCSS.CssParsing.CssParser.Parse(currentStyle);

            Css.SetStyleSheet(this, stylesheet);
        }

        public string currentStyle = @"
.important
{
    BackgroundColor: Red;
    FontSize: 25;
    WidthRequest: 200;
}
Label
{
    TextColor: Red;
    FontSize: 25;
}
Button
{
    TextColor: Blue;
    BackgroundColor: Black;
}
";
    }
}