How to get started with .NET MAUI

.NET MAUI is still in preview and the team at Microsoft continuously releases changes. Some tools, features, and steps mentioned in this post may change in the future.

This tutorial provides an overview of how to get started with .NET MAUI, or .NET Multi-platform APP UI (MAUI), which is a cross-platform framework for creating native mobile and desktop apps. .NET MAUI is the evolution of Xamarin.Forms, and is currently available in Preview 5.

To find out more about .NET MAUI and how it came to be, I recommend reading my blog post What is .NET MAUI? before continuing with this tutorial.

We will cover:

  • Setting up your environment
  • Creating your first .NET MAUI application
  • Writing in C# vs. XAML

Environment Setup

Before starting with a .NET MAUI project, we must first install all the proper dependencies. Microsoft has made this easy for us with the dotnet tool that evaluates your system. This tool will detect any problems and either offer to fix them for you or suggest a way for you to fix them yourself.

First, install the tool:

dotnet tool install -g Redth.Net.Maui.Check

Next, run the tool using the command:

maui-check

Follow the instructions given in the tool to get everything you need to start working with .NET MAUI:

MAUI Check tool screenshot

For the best development experience with .NET MAUI, I recommend using Visual Studio.

Microsoft currently recommends starting with Visual Studio 2019 16.11 Preview 2 to develop .NET MAUI applications. Full support for .NET MAUI will be available in Visual Studio 2022, now in preview.

Install the following workloads with Visual Studio:

  • Mobile development with .NET
  • Universal Windows Platform development
  • Desktop development with C++
  • .NET Desktop Development

Visual Studio workloadsSource: Microsoft

To run and debug in an Android emulator, set up an emulator within Visual Studio following this guide.

Once you have installed all that and the maui-check succeeds, you are ready to create your first .NET MAUI application.

Create a new MAUI app

This guide will use Visual Studio to create our first .NET MAUI application. However, you can also create a new .NET MAUI application from the command line.

In Visual Studio 16.11 Preview 2, select Create a new project and search for MAUI, or choose Project Type > MAUI from the dropdown.

Create project

The generated templates contain two projects:

  1. .NET MAUI project - targeting Android, iOS, and MacCatalyst
  2. WinUI Project - for Windows desktop applications

New project structure

The team works hard to consolidate all the projects into one to build and deploy across all platforms. The final consolidation will come in later versions.

Run the application by selecting the target device, such as Android Emulator, in the Visual Studio toolbar dropdown next to the Start button.

The application is a simple Hello World counter app with a button to increase the counter.

Template app image

Congratulations! You have created and run your first .NET MAUI application!

There are currently a few bugs in the layout of the template application. (issue #1382)

Fix the layout issues

The two issues in the template application are as follows:

  • Image does not show
  • Numbers with multiple digits are cut off at the first digit

To fix this, we can change the layout from the StackLayout in MainPage.xaml to a VerticalStackLayout, newly introduced in .NET MAUI remove each Grid.Row.

See this commit on my GitHub for the full details of the change.

Troubleshooting

As is to be expected with any preview, there are some issues you may have to address before you can fully get the project up and running. Below are the issues I ran into when writing this blog post.

Issue: Android Emulator crashes after launch

To fix this, disable XAML Hot Reload in Visual Studio and follow the instructions in this comment from the existing issue.

Issue: Previous installations of .NET 6 Preview 4 cause issues in .NET 6 Preview 5

See the Microsoft documentation here.

I expect the team to continue working through all the issues leading up to General Availability in November.

Using C# instead of XAML

As a C# developer with little experience using Xamarin and XAML, I am most excited about the ability to define pages in .NET MAUI applications using C#. The existing examples and templates get you started using the traditional XAML-based approach, carried over from Xamarin.Forms. In Xamarin.Forms, XAML defines the visual contents and works with a C# code-behind file. In .NET MAUI, you now have the option of using fluent C# or XAML to define the visual contents of a page.

To translate the template from XAML to C#, follow the steps below or get the complete source code from my GitHub

Steps

To use fluent C# to define the UI of the template .NET MAUI app, we will change:

  • App
  • MainPage
  • Startup

Note: The two projects in the template (.NET MAUI and WinUI) share the App, MainPage, and Startup files. Any changes will automatically be reflected across both.

  1. Delete App.xaml and the code-behind App.xaml.cs.

Note: In Visual Studio, the code-behind file is nested under the App.xaml. Deleting a XAML file in Visual Studio will automatically delete the associated code behind it._

  1. Create a new class called App.cs with the following content:

    using Microsoft.Maui;
    using Microsoft.Maui.Controls;
    using Microsoft.Maui.Graphics;
    using System.Collections.Generic;
    
    namespace GettingStartedMaui
    {
        public class App : IApplication
        {
            List<IWindow> _windows = new List<IWindow>();
            public IReadOnlyList<IWindow> Windows => _windows.AsReadOnly();
    
            public App(IImageSourceServiceConfiguration imageConfig)
            {
                imageConfig.SetImageDirectory("Assets");
            }
    
            public IWindow CreateWindow(IActivationState activationState)
            {
                var window = new Window(new MainPage());
                _windows.Add(window);
                return window;
            }
        }
    }
    
  2. Add the Extension Service Provider Factory to the app configuration in Startup.cs. This enables dependency injection for the ImageSourceServiceConfiguration used in the step above.

    appBuilder.UseMicrosoftExtensionsServiceProviderFactory();
    
  3. Delete MainPage.xaml and the code-behind MainPage.xaml.cs.

  4. Create a new class called MainPage.cs with the below content:

    using Microsoft.Maui;
    using Microsoft.Maui.Controls;
    using Microsoft.Maui.Graphics;
    
    namespace GettingStartedMaui
    {
        public partial class MainPage : ContentPage
        {
            public MainPage()
            {
                BackgroundColor = Color.FromArgb("#512bdf");
    
                var verticalStack = new VerticalStackLayout() { Spacing = 20 };
    
                verticalStack.Add(new Label
                {
                    Text = "Hello, World!",
                    FontSize = 32,
                    HorizontalOptions = LayoutOptions.CenterAndExpand,
                    TextColor = Colors.White
                });
                SemanticProperties.SetHeadingLevel((BindableObject)verticalStack.Children[verticalStack.Children.Count - 1], SemanticHeadingLevel.Level1);
    
                verticalStack.Add(new Label
                {
                    Text = "Welcome to .NET Multi-platform App UI",
                    FontSize = 16,
                    HorizontalOptions = LayoutOptions.Center,
                    TextColor = Colors.White
                });
    
                var counterLabel = new Label
                {
                    Text = "Current count: 0",
                    FontSize = 18,
                    FontAttributes = FontAttributes.Bold,
                    HorizontalOptions = LayoutOptions.Center,
                    TextColor = Colors.White
                };
    
                var button = new Button
                {
                    Text = "Click me",
                    HorizontalOptions = LayoutOptions.Center,
                    TextColor = Colors.White,
                    BackgroundColor = Color.FromArgb("#2b0b98"),
                    Padding = new Thickness(14, 10)
                };
    
                var count = 0;
                button.Clicked += (sender, args) =>
                {
                    count++;
                    counterLabel.Text = $"Current count: {count}";
                };
    
                verticalStack.Add(counterLabel);
                verticalStack.Add(button);
                verticalStack.Add(new Image { Source = "dotnet_bot.png", WidthRequest = 300, HorizontalOptions = LayoutOptions.Center });
    
                Content = new ScrollView
                {
                    Padding = 30,
                    Content = verticalStack
                };
            }
        }
    }
    
  5. Clean and rebuild the project.

You now are using fluent C# with your .NET MAUI application!.

Take a look at the .NET MAUI GitHub for future updates and news on what is next with .NET MAUI.


Attributions:
  1. undefined by undefined