Building a razor engine for Xamarin.Forms

05 Jan 2020

Xaml and html are both markup languages that can become very verbose when working on large projects. One of the things that has helped improved the expressiveness of html in the .NET world is ASP.NET’s razor engine. Xaml so far doesn’t have anything like the razor engine, so I decided to see what it would take to build something like razor that could be used with any Xaml project, just like how you can use static html with razor.

Below is from the readme, you can also try it interactively at the bottom of the page.

Additionally, I really hate writing

<StackLayout>
    <Label Text="First Name"/>
    <Entry Text="{Binding FirstName}"/>
    <Label Text="Last Name"/>
    <Entry Text="{Binding LastName}"/>
    <Label Text="Age"/>
    <Entry Text="{Binding Age}"/>
</StackLayout>

over and over again

I’d rather write this:

<local:Entry Caption="First Name" Text="{Binding FirstName}"/>
<local:Entry Caption="Last Name" Text="{Binding LastName}"/>
<local:Entry Caption="Age" Text="{Binding Age}"/>

We can do this by writing this in our Templates.taml file:

@Entry(string Caption, string Text)
{
    <StackLayout>
        <Label Text="@Caption"/>
        <Entry Text="@Text"/>        
    </StackLayout>
}

This will generate the desired control as seen above

Here is an example:

example;

Try it out for yourself!

Loading...

Built with <3 using Blazor

Recent Blogs