Xaml v Code

I still see a fair amount of Xamarin Forms UI written in C# code. If you are not that familiar with Xaml then it may seem to make sense to code up your views this way, but you will be missing out on the benefits of Xaml. Not only that but there are some really exciting new features which make Xaml an even better way to express your views which I will discuss shortly.

I was going to define the benefits of Xaml but Charles Petzold has done a great job in the Preview of his forthcoming book, Creating Mobile Apps with Xamarin.Forms. There are some great chapters on Xaml and his ‘Xaml v Code’ chapter succinctly sums up why we should all be using Xaml rather than code.

“You will find that XAML provides a more succinct and elegant definition of the user interface, and has a visual structure that better mimics the tree organisation of the visual elements on the page. XAML is also generally easier to maintain and modify than equivalent code. “

I would go further and say that, with regards to MVVM in particular, Xaml defines the template for the view, which is a visualisation of your view model. This template should be expressed in markup in much the same way that we define views in the html. It provides a much more expressive way to ‘declare’ the view in a way that allows you to lay it out in a declarative manner, rather than imperatively in code. A code-based approach tends to lead the developer to ‘program’ the layout with logic, which might include loops or conditional code mingled with the layout code. With Xaml the declarative approach allows you to focus on the layout and provide better reusable solutions where logic is required in the form of behaviours, markup extensions and converters. It also allows you to think more clearly about the bindings and the relationship with the view model. Further more Xaml allows you to define data bindings and express properties in a much more succinct manner.

For example in code you can not define bindings in-line with the layout like this.

    Content = new StackLayout
    {
        Orientation = StackOrientation.Horizontal,
        Children =
        {
            new Label
            {
                Text = ?? can not bind here
            }
        }
    };

You have to create the label as a separate variable so that you can call SetBinding and then add that variable into the layout like this.

    var label = new Label();
    label.SetBinding(Label.TextProperty, new Binding("Name"));

    Content = new StackLayout
    {
        Orientation = StackOrientation.Horizontal,
        Children =
        {
            label
        }
    };

This I find very irritating and before long you have some very unwieldy code. In Xaml bindings are defined right in the property declaration so everything fits very neatly into layout declaration like this:

    <StackLayout Orientation="Horizontal">
      <Label Text="{Binding Name}" />
    </StackLayout> 

I’m sure you’ll agree that this is more succinct and easier to follow that the code above.

I come from a WPF background. I know that most WPF developers would find it very strange and perhaps be horrified to find anyone trying to define all their views in code. A receipt for disaster almost as your application and complexity grows.

I think one of the reasons why some developers have adopted the code approach is due to many of the early examples being code based due to the lack of intellisense and tooling support for Xaml with Xamarin Forms. This is no longer the case. Xamarin Studio has, since I’ve used it, always provided intellisense for Xaml. Visual Studio now has first class intellisense support with the release of the Xamarin Mobile Essentials Productivity Tools. If you haven’t already installed this then do so now. In additional if you are a R# user, which I strongly recommended for your own sake, it also provides fantastic tooling and intellisense support in the Xaml editor. Namespaces are auto resolved, advanced colour picker for colour selection, code correction and warnings all feature in the editor. In fact it is as good as you would get in WPF.

One other thing that I discovered recently which I am very excited about is support for intellisense for bindings. By that I mean the ability to explore the properties that are available to you on the type that your view will be bound to through its binding context. In WPF this is done using the following declaration:

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewModels="clr-namespace:Silkweb.Mobile.MountainWeather.ViewModels;assembly=Silkweb.Mobile.MountainWeather"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type=viewModels:ForecastViewModel, IsDesignTimeCreatable=False}"

If you are not familiar with this the d: namespace provides some design-time support features, one of which is to define a design time data context for the type you will be binding to. The mc: namespace provides an Ignorable property that allows you to tell the xaml parser to ignore certain namespaces at runtime, namely the d: namespace. This all works in WPF and it also works in Xamarin Forms in design time to. However at runtime you will get an compilation error saying Markup Extension not found for d:DesignInstance.

Fortunately this has now been resolved with the help of Xaml Conditional Compilation (xcc) by firstfloorsoftware. You can find more about this on this forum post, which got me very exited about this feature. I followed the helpful Xamarin Forms how to. One additional thing you need to do though that I discovered here is you need to add the following Property Definition into any projects where you’re Xaml exists.

<XccRemoveIgnorableContent>True</XccRemoveIgnorableContent>

(Note: Make sure you follow this here).

I’m note sure why this isn’t documented or added as part of the install, but I guess this is very early days for this feature.

With this in place and the above namespaces and Design Instance defined I can now define Binding expressions and browse the types properties like this:

1
Even better I can even explore nested Properties of complex property types like this:

Screen Shot 2015-03-17 at 22.37.07

And if any of the bindings are invalid I get a warning with a squiggly line like this:

2

This is something you don’t even get if you try to define bindings in code, where you are restricted to using magic strings.

There is of course no designer yet for Xamarin Forms, but I don’t see that as an issue really. I never use the designer much in WPF really, preferring to define the Xaml by hand, similarly to how you would define Html in the web world. The designer is occasionally useful but it’s actually much easier to visualise what you are doing simply by looking at the Xaml. This can not be done quite so easily in code.

If you are still defining your views in code then you should consider embracing Xaml and it’s benefits. It will actually make you a better developer.

11 thoughts on “Xaml v Code

  1. The concept of creating a view in code horrifies me. What would be nice though is a Blend-like tool in which you define the UI in the XAML pane and you get to see the equivalent representation across the target device(s) in an adjacent pane(s). Not asking for much am I? 🙂

    Like

  2. If i make a typo in the xaml i get an error *at runtime* (on iOS that is, i don’t know about other platforms). This suggests that the xaml is parsed at runtime and not at compile/build. This has to be slower than pure code. What do you think? (But i still use xaml 🙂

    Like

      1. “…and it is parsed again at runtime”. This has te be slower than code only design.

        If I use a property that doesn’t exist, ie Tekst instead of Text, I get no warning/error at compile/build time, but at runtime I get ‘Xamarin.Forms.Xaml.XamlParseException: Position 48:28. No Property of name Tekst found’ (i’m using vs2013)

        Like

  3. I think the True may no longer be needed. I put in the namespace additions at the top of my XAML and was able to get intellisense and no build errors. I did not install the XCC stuff via nuget and I am using Visual Studio 2013.

    Like

      1. I am on 1.4.0.0. This appears to be a false positive as I did a clean of the solution and a build and now the screen is failing for the bug listed above. What a bummer 😦

        Like

      2. Ah well, nearly. I have found the XCC solution to work really well though, so perhaps give it a go. The only downside is it doesn’t work in Xamarin Studio, but I don’t use that anymore.

        Like

  4. Here is why I see people doing this:

    1) Xamarin’s sheer oversight of a XAML editor/designer is asinine. No one in 2015 wants to build UI’s without a designer
    2) XAML albeit succinct, is still a completely new language. Sure it’s XML, it’s simple, but you have to relearn the names of all the controls, layout, etc.
    3) While doing it in C# is ass-backwards in my opinion, it can easily overpower the time sync required to learn/debug/design XAML.

    Either way you have to “RUN” to preview your designs. There is no substitute for a good UI designer such as the XCODE storyboard feature, or the Visual Studio standard winforms designer.

    You are quibbling over the leftovers XAML vs C# = they both are terrible for UI, you should use a designer if you really want “RAD” development

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s