Loading...

UI Development in MAUI Apps with FmgLib.MauiMarkup


Make UI development more efficient in MAUI applications with FmgLib.MauiMarkup library.

Streamlining .NET MAUI Development with FmgLib.MauiMarkup: A Comprehensive Guide

.NET MAUI is a fantastic framework that allows you to develop iOS, Android, Windows, and macOS applications from a single codebase. Traditionally, the user interfaces (UIs) of MAUI applications are defined using XAML. However, some developers may feel the limitations or complexity of XAML. This is exactly where the FmgLib.MauiMarkup library comes in!

In this blog post, we'll dive deep into FmgLib.MauiMarkup, discussing how it's used, its benefits, how it frees you from XAML dependency, and its impact on performance.

What is FmgLib.MauiMarkup?

FmgLib.MauiMarkup is a library that allows you to create .NET MAUI UIs more easily and fluidly with C# code. It offers an alternative to XAML-based declarative UI definition. Essentially, it enables you to create MAUI's built-in controls and layouts in a fluent API style through C# extension methods. This allows you to write your UI with more readable and maintainable C# code.

Why Should You Use FmgLib.MauiMarkup?

There are many potential benefits to using FmgLib.MauiMarkup:

  • Freedom from XAML: If you dislike XAML or prefer a more “code-first” approach, this library is for you. By building your UI entirely in C#, you can escape the syntax and compile-time limitations of XAML.

  • More Readable and Fluent Code: Thanks to the Fluent API, defining your UI hierarchy and properties with chained method calls is quite intuitive. This can increase code readability, especially in complex UIs.

  • Ease of Dynamic UI Creation: Building UI with C# increases the flexibility to dynamically add, remove, or modify UI elements and their properties at runtime based on conditions.

  • Developer Experience: Auto-completion (IntelliSense) support can be more robust than XAML because C# type safety and method signatures are more explicit.

  • Single Language Knowledge: A developer who knows only C# can write both the backend code and the UI in a single language, which can reduce the learning curve.

How to Use FmgLib.MauiMarkup

Getting started with FmgLib.MauiMarkup is quite simple. First, you need to add the FmgLib.MauiMarkup NuGet package to your project.

Install-Package FmgLib.MauiMarkup

Then, you can start building MAUI UI elements with C# code. Here's a simple example:

Traditional XAML Approach: MainPage.xaml:

<!-- MainPage.xaml -->
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiApp1.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Padding="30,0"
            Spacing="25">
            <Image
                Source="dotnet_bot.png"
                HeightRequest="185"
                Aspect="AspectFit"
                SemanticProperties.Description="dot net bot in a hovercraft number nine" />

            <Label
                Text="Hello, World!"
                Style="{StaticResource Headline}"
                SemanticProperties.HeadingLevel="Level1" />

            <Label
                Text="Welcome to &#10;.NET Multi-platform App UI"
                Style="{StaticResource SubHeadline}"
                SemanticProperties.HeadingLevel="Level2"
                SemanticProperties.Description="Welcome to dot net Multi platform App U I" />

            <Button
                x:Name="CounterBtn"
                Text="Click me" 
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnCounterClicked"
                HorizontalOptions="Fill" />
        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

MainPage.xaml.cs:

namespace MauiApp1;

public partial class MainPage : ContentPage
{
	int count = 0;

	public MainPage()
	{
		InitializeComponent();
	}

	private void OnCounterClicked(object sender, EventArgs e)
	{
		count++;

		if (count == 1)
			CounterBtn.Text = $"Clicked {count} time";
		else
			CounterBtn.Text = $"Clicked {count} times";

		SemanticScreenReader.Announce(CounterBtn.Text);
	}
}

FmgLib.MauiMarkup C# Approach (MainPage.cs):

using FmgLib.MauiMarkup; // Required using directive
namespace MauiAppMarkup1;

public partial class MainPage : ContentPage, IFmgLibHotReload
{

    private int _count = 0;
    private Label CounterLabel;

    public MainPage()
    {
        this.InitializeHotReload();
    }

    public void Build()
    {
        this
        .Content(
            new ScrollView()
            .Content(
                new VerticalStackLayout()
                .Spacing(25)
                .Padding(10)
                .Children(
                    new Label()
                    .Text("Hello, World!")
                    .FontSize(32)
                    .CenterHorizontal()
                    .SemanticHeadingLevel(SemanticHeadingLevel.Level1),

                    new Label()
                    .Text("Welcome to FmgLib .NET MAUI Markup App")
                    .FontSize(18)
                    .CenterHorizontal()
                    .SemanticDescription("Welcome to dot net Multi platform App U I")
                    .SemanticHeadingLevel(SemanticHeadingLevel.Level1),

                    new Label()
                    .Text("Current count: 0")
                    .FontSize(18)
                    .FontAttributes(Bold)
                    .CenterHorizontal()
                    .Assign(out CounterLabel),

                    new Button()
                    .Text("Click me")
                    .CenterHorizontal()
                    .SemanticHint("Counts the number of times you click")
                    .OnClicked((s,e) =>
                    {
                        _count++;
                        CounterLabel.Text = $"Current count: {_count}";
                        SemanticScreenReader.Announce(CounterLabel.Text);
                    }),

                    new Image()
                    .Source("dotnet_bot.png")
                    .SizeRequest(250, 310)
                    .CenterHorizontal()
                    .SemanticDescription("Cute dot net bot waving hi to you!")
                )
            )
        );
    }
}

As you can see in the example above, thanks to extension methods like .Spacing(), .Padding(), .Children(), .Text(), .FontSize(), and .CenterHorizontal(), we can define UI elements in a chained manner. We can easily bind events using the OnClicked() method.

Freedom from XAML

One of the most appealing features of FmgLib.MauiMarkup is its ability to completely free you from XAML. In traditional MAUI development, XAML files are parsed at compile time and combined with the code-behind. With FmgLib.MauiMarkup, your UI definition occurs directly within C# code. This eliminates the need to learn and debug XAML's XML-based syntax.

Escaping XAML can be beneficial in the following situations:

  • Those who prefer a single language: If you don't want to learn or use an additional markup language.

  • Dynamic and conditional UI: When you need to programmatically create or modify UI elements based on complex conditions.

  • Code generation: In scenarios where the UI is automatically generated with C# code (e.g., using a design tool).

Performance Impact

The performance impact of FmgLib.MauiMarkup is generally minimal and negligible for most applications. Here's what to consider:

  • Compile Time: While XAML is parsed and merged with the code-behind at compile time, FmgLib.MauiMarkup directly executes C# code. This usually doesn't require an extra compilation step as it's part of the C# compilation. Theoretically, compile time might be slightly faster with FmgLib.MauiMarkup because the XAML parsing step is avoided.

  • Runtime: Both XAML and FmgLib.MauiMarkup ultimately use the same native rendering mechanisms to create MAUI's fundamental UI elements. This means the resulting UI tree and how it's drawn on screen are fundamentally the same. While FmgLib.MauiMarkup creates UI elements through a chain of C# method calls, these operations are very fast and typically do not create a performance bottleneck.

  • Memory Usage: There might be a small difference, but this difference is not expected to have a significant impact on application performance on modern devices.

In summary, using FmgLib.MauiMarkup does not lead to a significant drop in your application's overall performance. Performance optimizations should generally be sought in areas like data processing, network requests, and overall application architecture, rather than the UI creation method.

Conclusion

FmgLib.MauiMarkup offers .NET MAUI developers a powerful and flexible alternative to XAML. Thanks to its C#-based, fluent API, you can create your UI in a more readable, manageable, and dynamic way. It's an excellent tool, especially for developers who want to avoid XAML or seek more flexibility in dynamic UI scenarios. The absence of a significant performance disadvantage makes it an attractive option for modern MAUI applications.

Try FmgLib.MauiMarkup in your project and see for yourself how it improves your development experience!