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!