Dynamic XAML in Xamarin.Forms Applications

Note: you can download the source code for this blog post here.

As you know, Xamarin.Forms application usually will generate code at compilation time using your XAML definition, and after building and distribution, the application is ready to be used. If you want to change the user interface dynamically or how it consumes data, you will need to start the cycle again. It can be time-consuming and too slow for small changes. You could use C# code to create your UI, but that’s an approach that is not used very often because it is so verbose and slow when viewing or debugging.

Template Engine Alternative

For one of my projects, I was looking for an alternative to this development cycle, some lightweight template engine that we can use to specify the UI externally and change it by sending a new template definition. For example, I need it for the DataTemplate in a ListView, not for the whole app. The goal was that the user could rewrite the information shown in those lists.
Checking some of the templating options, I thought that instead of using some text block with markers to be replaced, I could probably do the same with XAML as Xamarin does. After some research and doc reading (yep, I even read the docs!), the LoadFromXaml method was looking good.

How to Implement It

1 – Create an Object from XAML

My first attempt was to load some simple XAML like:

<Label Text="Hello dynamic world!" />

To a stack layout using:

var stackLayout = new StackLayout().LoadFromXaml("<Label Text=\"Hello dynamic world!\" />");

But it didn’t work. The problem was my assumption that LoadFromXaml would populate a StackLayout, but what it is doing is loading an object of the same type so that the following code would work:

var label = new Label().LoadFromXaml("<Label Text=\"Hello dynamic world!\" />");

After that, you can use the newly created object and add it to the children’s collection of any container.

2 – Data Binding

You can’t use dynamic objects as a source for data binding (at least not without creating your markup extension, which is not a trivial task), but you can use a dictionary even with a two-way data binding.
The code sample shows how a JSON object is converted to a dictionary and used as the binding context for the view and then converted back to a JSON object to get the updated values.

3 – Other Xamarin Mechanism

You can include styles, converters, and any other Xamarin functionality, adding the correct references at the beginning of your XAML file the same way you use it with any XAML.
The included code sample is a Xamarin.Forms app, in this app, we have two tabs, the first one with the dynamic XAML and the values as a JSON object.

>

The JSON would be deserialized to a dictionary called Values, so we can reference that dictionary as the data binding source.
The second tab will render the UI and load the values. When you navigate back to the definition, you will use the dictionary’s information to update your JSON object.
The critical part of the app is the LoadData method in the BrowseViewModel.cs file.
The section related to replacing the value inside the *Shell* (nothing to do with the Shell functionality in Xamarin) is because of the problem I mentioned earlier. I don’t know the control type, and because I need that information to call the LoadFromXaml method, I would create a content view as a container where I will put the XAML to be created, so I can call ”’new ContentView().LoadFromXaml”’

void LoadData()
{
    // Load values from Json
    var jsonData = Preferences.Get("JsonData", "{}");
    var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonData);
    Values.Clear();
    if (data != null)
    {
        foreach (var entry in data)
        {
            Values.Add(entry.Key, entry.Value);
        }
    }
    // Get the Xaml and put inside the shell
    var baseDefinition = Preferences.Get(nameof(XamlDefinition), "");
    XamlDefinition = XamlShell.Replace("{{content}}", baseDefinition);
    var contentView = new ContentView().LoadFromXaml(XamlDefinition);
    // Set DataBinding
    contentView.BindingContext = this;
    // Set the content on the view
    ContentPresenter?.Children?.Clear();
    ContentPresenter?.Children?.Add(contentView);
}

Drawbacks

With this technique, you can create a dynamic app, but keep in mind some of the issues you can encounter:

  • Development: it’s more challenging to preview your XAML and test it. You will need to create some dummy views if you want to try your XAML while working on your templates, which would be more time-consuming.
  • Debugging: you will not get any warnings when your XAML is wrong until you try to use it.
  • Performance: performance is worst because the creation of the UI is happening on the fly, and with compiled XAML, it happens at build time.

That’s it for now. Thanks for reading!

Picture of Rodrigo Juarez

Rodrigo Juarez

Rodrigo Juarez has over 25 years of experience in software development, specializing in Microsoft technologies. His mission is to solve complex problems for his clients, with a focus on results. He achieves this by applying the appropriate technology and using best practices to ensure the delivery of high-quality solutions. Over the past 6 years, Rodrigo has honed his skills in back-end development and in creating mobile applications, initially using Xamarin and now transitioning to .NET MAUI. He is a Lead Mobile Developer at Trailhead Technology Partners and the co-author, along with Jesse Liberty, of the book ".NET MAUI for C# Developers"

Free Consultation

Sign up for a FREE consultation with one of Trailhead's experts.

"*" indicates required fields

This field is for validation purposes and should be left unchanged.

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Adding a New Android Permission in a Xamarin App

As you know, Android is always adding features in its new versions and now the Post Notifications permission has been introduced from Android 13. In this blog, we are going to explore how to request it in our Xamarin.Android projects. Sampl

Read More

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.