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!

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:

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

Ready to come with us? 

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! 

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! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

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

Ready to come with us? 

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 contact form. 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! 

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

Thank you message.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.