C# Markup

Xamarin.Forms 4.6 introduced C# Markup, a set of fluent helpers and classes that aim to make UI development in C# a joy.

C# Markup helps developers write concise declarative UI markup and cleanly separate it from UI logic, all in C#. Developers get to enjoy C#’s first-class IDE support when writing markup. A single language for markup and logic reduces friction, markup scattering and cognitive load; there is less or no need for language bridging mechanisms like separate converters, styles, resource dictionaries, behaviours, triggers and markup extensions.

Example

Let’s introduce the main features of C# Markup by building this Twitter search page:

Twitter Search Example

The full source of this example can be found here.

Build Top-Down with Hot Reload

C# Markup makes it easy to write markup using a top-down approach – so it reads like a story, filling in details while you progress. This short video shows the process from start to finish in 2.5 minutes (using DebugRainbows and LiveSharp):

Note that this video is unedited and realtime; it was recorded in one go by replaying git commits from the command line.

Write the Page – Like a Story

At the highest level the page contains a header, search results and a footer. So, if we structure the markup top-down – to make it read like a story – the initial markup could be:

SearchPage.cs

using Xamarin.Forms.Markup;

public partial class SearchPage
{
    void Build() => Content = 
        new StackLayout { Children = {
            Header,
            SearchResults,
            Footer
        }};

    StackLayout Header => new StackLayout { };

    CollectionView SearchResults => new CollectionView { };

    Label Footer => new Label { };
}

The void Build() => Content = pattern is a convention that lets you use LiveSharp for stateful hot reload of C# Markup. If you don’t plan on using LiveSharp, omit the Build() method and put the Content assignment in the page constructor.

For now C# Markup is an experimental feature. So we need to set a flag to enable the feature:

App.cs

Device.SetFlags(new string[]{ "Markup_Experimental" });

#developers #xamarin.forms #c# markup #coded ui #programming-c #csharp

Introducing C# Markup for Xamarin.Forms
4.05 GEEK