Getting started with Microsoft .NET MAUI

//Getting started with Microsoft .NET MAUI

.NET Multi-platform App UI (.NET MAUI) is an evolution of the Xamarin.Forms toolkit. With developer productivity in mind, MAUI simplifies the project structure into a single project to target multiple platforms (Android, iOS, macOS, and Windows).

In this article, we’ll explore MAUI and learn to build a simple to-do list app.

The following sections will guide you through getting started with .NET MAUI:

  • What’s .NET MAUI, who is it for, how does it work?
  • Advantages of MAUI over other cross-platform frameworks
  • Installing prerequisites for cross-platform development with MAUI
  • Installing MAUI
  • Building a to-do list app
  • Troubleshooting

Technical Requirements

The article is primarily aimed at .NET developers with some experience with Xamarin and .NET.

For the to-do app, a Windows 10 development environment is required since Visual Studio for Mac support for .NET MAUI is planned for a future release.

Ideally, you should have a macOS device with Xamarin.iOS and Xcode installed connected to your Windows 10 environment. This is because you’ll need it compile and use the iOS simulator. With this set up, i.e. Windows and Mac, we can test the to-do app on multiple platforms (Android, iOS, macOS, and Windows).

Important Note

Visual Studio 2022 can only currently deploy .NET MAUI iOS apps to the iOS simulator, and not to physical devices.

You can find the code used in this article through the following GitHub link: https://github.com/PacktPublishing/PacktPlus/tree/main/MAUI/GettingStartedonMAUI

What’s .NET MAUI, who is it for, how does it work?

.NET MAUI is a cross-platform framework for creating native mobile and desktop apps with C# and XAML.  It works as an abstraction layer that manages communication of shared code with underlying platforms such as Android, iOS, macOS, and Windows.

.NET MAUI allows you to create native UI on each platform and write business logic in C# that is shared across platforms. It is built on top of .NET, which means it handles tasks such as memory allocation, garbage collection, and interoperability with the Android, iOS, macOS, and Windows platforms.

.NET MAUI is for developers that want to write cross-platform apps using C# from a single shared codebase in Visual Studio

If you have previously used Xamarin.Forms to build cross-platform user interfaces, you will notice many similarities with .NET MAUI. In fact, .NET MAUI is the evolution of Xamarin.Forms. However, it simplifies the project structure into a single project to target multiple platforms. In Xamarin.Forms, you have one project for each target platform and another project for a shared code base:

Figure 1 – Comparing the solution structure between Xamarin.Forms (left) and .NET MAUI (right)

.NET MAUI lets you add resources like images, fonts, or translation forms once to a single project without needing to do it for each platform separately. In comparison, when using Xamarin.Forms, you need to add each resource to each platform separately. This adds extra work for you and your team. For example, in Figure 2, you can see that in Xamarin.Forms you have to add the check.png image to 3 different projects, whilst in .NET MAUI, you add it to a single project.

Figure 2 – Comparing the solution structure between Xamarin.Forms (left) and .NET MAUI (right)

However, .NET MAUI still lets you work with the native underlying operating system APIs. Under the Platforms folder, you can add source code files for a specific operating system and access the native APIs:

Figure 3 – The Platforms folder where you can add source code files for a specific operating system

Advantages of MAUI over other cross-platform frameworks

Choosing the right framework is an important step in the business decision process. It can impact in the long term the cost and effectiveness of your app and your company. Opting for a framework where there is a high demand of developers and a low offer can significantly increase your operational cost and jeopardize your daily operation when a developer decides to leave the company.

.NET MAUI uses C# for coding, has a strong community, and contains a single tech stack for faster development. It is after all, commercially supported by Microsoft, while some cross-platform frameworks depend on community development and do not have  consistent release intervals.

Why should you choose .NET MAUI over other cross-platform frameworks?

Some frameworks, such as React Native, are not a fully cross platform app framework. To use some functions like camera or accelerometer you need to build separate code for Android and iOS. .NET MAUI provides cross-platform APIs for native device features. For example, you have access to,

  • Sensors, such as the accelerometer, compass, and gyroscope on devices.
  • Device’s network connectivity state and detect changes.
  • built-in text-to-speech engines to read text from the device.

Where other frameworks lack support to other platforms such as Android TV and Apple TV, .NET MAUI thrives. .NET MAUI apps can be written for a wider range of platforms than most other cross-platform frameworks:

  • Android
  • iOS 10
  • macOS
  • Windows desktop and the Universal Windows Platform (UWP).
  • Tizen
  • Linux

.NET MAUI includes support for .NET and XAML hot reload, which enables you to modify your source code while the app is running. You do not need to manually pause or hit a breakpoint. Your code edits can be applied to your running app speeding up the development process.

Installing prerequisites for cross-platform development with MAUI

The process for installing MAUI consists of some prerequisites being installed first in addition to some extensions and workloads. You should install the following prerequisites:

  • Visual Studio 2022 Preview
  • The Visual Studio extension: Single-project MSIX Packaging Tools
  • Microsoft Edge WebView2

Important Note

Since MAUI is in a preview release, the requirements and installation instructions will change as Microsoft releases updates. Always check the official Microsoft .NET MAUI documentation to stay up-to-date.

Installing Visual Studio 2022 preview and workloads

To create.NET MAUI apps, you need to download and install the latest Visual Studio 2022 Preview with the following workloads installed:

  • Mobile development with .NET
  • Universal Windows Platform development
  • Desktop development with C++
  • .NET Desktop Development
  • NET and web development (required for Blazor Desktop and the BlazorWebView control)

Figure 4 – The workloads installation window

If you have already installed the latest Visual Studio 2022 Preview, you can add those workloads by opening Visual Studio 2022 Preview and clicking on the Tools menu, and selecting the option Get Tools and Features…

Figure 5 – Adding new workloads on Visual Studio 2022

Visual Studio 2022 Preview comes with the latest preview of .NET 6, which is also a requirement for .NET MAUI.

Installing the Single-project MSIX Packaging Tools for VS 2022 extension

Next, you must install the Visual Studio extension Single-project MSIX Packaging Tools for VS 2022 to create apps that target Windows UI Library (WinUI) 3.

This extension provides Visual Studio 2022 support for working with and debugging Windows apps that use Single-project MSIX Packaging. A MAUI dependency.

Installing Microsoft Edge WebView2

The Microsoft Edge WebView2 control allows you to embed web technologies (HTML, CSS, and JavaScript) in your native apps. This control is a prerequisite for .NET MAUI.

To install the package, follow the steps below:

  1. Open the Microsoft Edge WebView2 download page.
  2. Scroll down to the bottom and click the Download button from the section Evergreen Bootstrapper.
  3. Read and accept the License Terms.
  4. Run the downloaded installer as administrator.

Figure 6 – Download page for WebView2 Runtime dependency

Installing MAUI

Once the prerequisites are installed, the last step is installing the .NET MAUI workloads. This process is straightforward, and it only takes a single command to run in a command prompt or terminal.

You can also verify your development environment and install any missing components by using the maui-check utility. We will cover it later in this section.

Installing the .NET MAUI workloads

In a command prompt or terminal, run the following command to install the .NET MAUI workloads

dotnet workload install maui

If you have trouble with the dotnet command not being found, then open the Developer Command Prompt for VS 2022 Preview and try it again.

Verifying and installing missing components maui-check utility

The maui-check utility is a command line tool that verifies your development environment and installs any missing components.

Run the following .NET Command Line Interface (.NET CLI) command to install the maui-check utility:

dotnet tool install -g redth.net.MAUI.check

If you already have a previous version of maui-check installed, update it to the latest version with the following .NET CLI command:

dotnet tool update -g redth.net.MAUI.check

Finally, run the following command to check your development environment:

maui-check

If any tools and SDKs required by .NET MAUI are missing, maui-check will prompt you to install them.

Figure 7 – Message from maui-check with prompts to install missing dependencies

Once you install the missing components, run maui-check again to ensure that your environment has the latest tools and SDKs required by .NET MAUI.

You should see the message Congratulations, everything looks great! when every dependency has been installed.

Figure 8 – Message from maui-check confirming that workloads are all installed

Building a to-do list app

In this section, you will learn how to create and run your first.NET MAUI app. This application will function as a simple to-do list where you can add new tasks, mark them as done, and list the existing ones.

There are two options to create a .NET MAUI project:

  1. Using the .NET CLI
  2. Using the .NET MAUI App template in Visual Studio 2022 (Preview)

Choose the option that best suits you to create a new .NET MAUI project.

Option 1: Creating a new .NET MAUI project using .NET CLI

You are going to create a new .NET MAUI project using .NET CLI by carrying out the following steps:

  1. Open a new command prompt or terminal, and run the following command to create a new .NET MAUI project:
dotnet new MAUI -n TodoMAUI

You should see the following message when the command runs successfully:

The template ".NET MAUI App" was created successfully.
  1. Next, you need to run the following commands to change directory to the newly created directory and restore its dependencies:
cd TodoMAUI

dotnet restore

You should see the following message when the command runs successfully:

PS C:\Git\TodoMAUI> dotnet restore
  Determining projects to restore...

  Restored C:\Git\TodoMAUI\TodoMAUI.WinUI\TodoMAUI.WinUI.csproj (in 343 ms).

  Restored C:\Git\TodoMAUI\TodoMAUI\TodoMAUI.csproj (in 731 ms).

Now, using Visual Studio 2022 (Preview), you can open the solution file TodoMAUI.sln.

Option 2: Creating a new .NET MAUI project using Visual Studio 2022 (Preview)

You are going to create a new .NET MAUI project using Visual Studio 2022 (Preview) by carrying out the following steps:

  1. Launch Visual Studio 2022, and in the Start window click Create a new project to create a new project:

Figure 9 – The start window in Visual Studio 2022

  1. In the Create a new project window, select MAUI in the Project type drop-down, select the .NET MAUI App template, and click the Next button:

Figure 10 – Selecting the .NET MAUI App template in Visual Studio 2022

  1. In the Configure your new project window, name your project TodoMAUI, choose a suitable location for it, and click the Create button:

Figure 11 – Configure your new project window in Visual Studio 2022

  1. Wait for the project to be created, and its dependencies to be restored:

Figure 12 – .NET MAUI project with its dependencies restored

Understanding the .NET MAUI solution structure

If you have worked with Xamarin.Forms before, you are going to find many similarities with .NET MAUI, however now everything is in a single project:

Figure 13 – A typical .NET MAUI solution

A typical .NET MAUI solution consists of the following structure:

  • The main project targeting the Android, iOS, and MacOS platforms.
  • One project targeting the Windows platform. This project be identified by the suffix .WinUI in the name.

Each project contains the following structure:

  • Dependencies: lists the NuGet Packages, Frameworks, and Analysers specific to the target platform
  • Platforms: where you can add code specific to a target-platform. For instance, you can add logic to the Android’s MainActivity class or styles in the Resources folder.
  • Resources: you can add cross-platform resources such as images, fonts, or translation files. .NET MAUI will automatically setup native hooks for the target platforms.
  • Startup.cs file: this is the entry point that initializes the app. Here you can register fonts, handlers, and custom control renderers.
  • App.xaml and App.xaml.cs files: here is where you define shared resources such as styles among the target platform and you define the UI for the initial page of the app.

Understanding Modern App Patterns

With .NET MAUI, you can use the modern app patterns that were extensively used in Xamarin.Forms. .NET MAUI supports both the existing Model-View-ViewModel (MVVM) and XAML patterns as well as future capabilities like Model-View-Update (MVU) with C#, or even Blazor.

First, you have the MVVM. This pattern helps to cleanly separate the business and presentation logic of an application from its user interface (UI). It mainly concentrates on data and how to decouple data from views. You can learn more from The Model-View-ViewModel Pattern – Xamarin | Microsoft Docs.

Next, .NET MAUI enables developers to write fluent C# UI and implement the MVU pattern. MVU promotes a one-way flow of data and state management, as well as a code-first development experience that rapidly updates the UI by applying only the changes necessary.

Below is an example in the MVU style:

readonly State<int> count = 0;

[Body]

View body() => new StackLayout

{

    new Label("Welcome to .NET MAUI!"),

    new Button(

        () => $"You clicked {count} times.",

        () => count.Value ++)

    )

};

In this tutorial, you will implement a to-do list app following the popular MVVM pattern.

Implementing the Model

Model classes encapsulate the app’s data. It usually includes a data model along with business and validation logic. Model classes are commonly used in conjunction with repositories that encapsulate data access and caching.

You are going to create a model for the to-do item and a repository for data access. Carry out the following steps:

  1. First, start by creating a new folder in the TodoMAUI project called Models.
  2. Next, create a new class called TodoItem:

using System;

namespace TodoMAUI.Models

{

    public class TodoItem

    {

        public Guid ID { get; set; }

        public string Name { get; set; }

        public string Notes { get; set; }

        public bool Done { get; set; }

    }

}

In our example, a to-do item is composed of a unique ID, a name, notes, and a Boolean member to mark the item as done.

  1. Now, create a new folder in the TodoMAUI project, called Repositories.
  2. Next, create a new class called TodoRepository:

using System;

using System.Collections.Generic;

using System.Linq;

using TodoMAUI.Models;

namespace TodoMAUI.Repositories

{

    public class TodoRepository

    {

        private TodoRepository() { }

        private static TodoRepository instance = null;

        public static TodoRepository Instance

        {

            get

            {

                if (instance == null)

                {

                    instance = new TodoRepository();

                }

                return instance;

            }

        }

    }

}

The TodoRepository is a Singleton implementation. Singleton is a design pattern. In this pattern, a class has only one instance in the application that provides a unique point of access to it. You are implementing a Singleton so you don’t have worry about creating a new instance of the TodoRepository every time.

Important Note

The example code above is not thread safe. Meaning two different threads could both call the TodoRepository and get unpredictable results. In another words, do not use the provided examples in a real-world application. You can learn more in the following article Singleton Design Pattern In C# (c-sharpcorner.com).

  1. Now, add a private collection member for holding the to-do items and the GetItems method to read all to-do items.

        private List<TodoItem> _todoItems = new List<TodoItem>();

        public List<TodoItem> GetItems()

        {

            return _todoItems.ToList();

        }

  1. Next, add the GetItemsNotDone method to read all pending to-do items:

        public List<TodoItem> GetItemsNotDone()

        {

            return _todoItems.Where(s => s.Done == false).ToList();

        }

  1. To view and edit the details of a specific to-do item, you need to create the GetItem which takes an id parameter:

        public TodoItem GetItem(Guid id)

        {

            return _todoItems.Where(i => i.ID == id).FirstOrDefault();

        }

  1. Finally, create the SaveItem and DeleteItem:

        public Guid SaveItem(TodoItem item)

        {

            if (item.ID != Guid.Empty)

            {

                _todoItems.Remove(item);

                _todoItems.Add(item);

                return item.ID;

            }

            else

            {

                item.ID = Guid.NewGuid();

                _todoItems.Add(item);

                return item.ID;

            }

        }

        public void DeleteItem(TodoItem item)

        {

            _todoItems.Remove(item);

        }

Implementing the View

The view is responsible for defining what the user sees on screen. Each view is defined in XAML. Ideally, it should contain a limited code-behind without business logic.

To list and edit a to-do item, you are going to create two views in the application. The first view, called Todo Item Page is responsible for showing the details of a to-do item and editing it. The second view, called Todo List Page, is responsible for listing all to-do items in the application.

Creating the Todo Item Page

We’ll start with the Todo Item Page. The Todo Item Page is responsible for showing the details of a to-do item and editing it. Carry out the following steps:

  1. Create a new folder in the TodoMAUI project, called Views.
  2. Next, create a content page called TodoItemPage by right clicking the Views folder, click Add, and click New Item. This will display the Add New Item dialog.
  3. In the Add New Item dialog, click Forms, and then Content Page. Enter “TodoItemPage” in the field Name, and click on the button Add:

Figure 14 – Adding a new Content Page

Now, things get a bit interesting. Since, at the time of writing this article, .NET MAUI is in preview, there is no Content Page template for .NET MAUI. The Content Page you have just created only works on Xamarin.Forms projects.

If you try to build the solution, it will fail:

error CS0246: The type or namespace name 'Xamarin' could not be found (are you missing a using directive or an assembly reference?)

error CS0246: The type or namespace name 'ContentPage' could not be found (are you missing a using directive or an assembly reference?)

error CS0246: The type or namespace name 'XamlCompilationAttribute' could not be found (are you missing a using directive or an assembly reference?)

error CS0246: The type or namespace name 'XamlCompilation' could not be found (are you missing a using directive or an assembly reference?)

error CS0103: The name 'XamlCompilationOptions' does not exist in the current context

Done building project "TodoMAUI.WinUI.csproj" -- FAILED.

What you should do is to migrate the Xamarin.Forms Content Page to .NET MAUI Content Page.

Migrating to .NET MAUI Content Page

The process to migrate the Xamarin.Forms Content Page to .NET MAUI Content Page is as follows:

  1. Replace Xamarin.Forms Xml namespaces.
  2. Change the Build Action to MAUIXaml.
  3. Replace the Xamarin.Forms using statements.
  4. Remove the XamlCompilation attribute.
  5. Update the .NET MAUI project file.

Let’s look at the steps:

  1. Double-click the TodoItemPage.xaml file and replace the Xamarin.Forms namespaces with the .NET MAUI corresponding ones:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/MAUI" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="TodoMAUI.Views.TodoItemPage">

  1. Open the Properties window (View > Properties Window, or Ctrl + W, P) and change the Build Action property to MAUIXaml. Additionally, ensure the Custom Tool property is empty.

Figure 15 – Updating the Build Action of the Content Page

  1. Double-click the TodoItemPage.xaml.cs file and delete the following using statements:

using Xamarin.Forms;

using Xamarin.Forms.Xaml;

  1. Add the following using statement to the TodoItemPage.xaml.cs file:

using Microsoft.MAUI.Controls;

  1. Remove the XamlCompilation attribute from the TodoItemPage.xaml.cs file:

[XamlCompilation(XamlCompilationOptions.Compile)]

Here’s what the TodoItemPage.xaml.cs file should look like:

using Microsoft.MAUI.Controls;

namespace TodoMAUI.Views

{

    public partial class TodoItemPage : ContentPage

    {

        public TodoItemPage()

        {

            InitializeComponent();

        }

    }

}

  1. Right-click the TodoMAUI project, then click Edit Project File. Now remove the Xml block below from the project file. After that, click the Save button (or Ctrl + S):

<ItemGroup>

  <MAUIXaml Update="Views\TodoItemPage.xaml">

    <Generator></Generator>

  </MAUIXaml>

</ItemGroup>

When you added a new Content Page from Xamarin.Forms, the project file was updated. However, .NET MAUI is smart enough to find new views added to the project. It means the project file does not need to reference views, nor classes.

  1. Now, build the solution. Everything should work accordingly.

Updating the Todo Item Page View

Now, you are going to add some fields and buttons to the Todo Item Page view. These fields will enable user to edit and remove a to-do from the list.

  1. Double-click the TodoItemPage.xaml file and replace update the Xaml with the following markup:

<?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="TodoMAUI.Views.TodoItemPage" Title="{Binding Name}">

    <ContentPage.Content>

        <StackLayout Margin="20" VerticalOptions="StartAndExpand">

            <Label Text="Name" />

            <Entry Text="{Binding Name}" />

            <Label Text="Notes" />

            <Entry Text="{Binding Notes}" />

            <Label Text="Done" />

            <Switch IsToggled="{Binding Done}" />

            <Button Text="Save" Clicked="OnSaveClicked" />

            <Button Text="Delete" Clicked="OnDeleteClicked" />

            <Button Text="Cancel" Clicked="OnCancelClicked" />

        </StackLayout>

    </ContentPage.Content>

</ContentPage>

  1. Double-click the TodoItemPage.xaml.cs file and update the existing code with the following:

using Microsoft.MAUI.Controls;

using TodoMAUI.Models;

using TodoMAUI.Repositories;

namespace TodoMAUI.Views

{

    public partial class TodoItemPage : ContentPage

    {

        public TodoItemPage()

        {

            InitializeComponent();

        }

        async void OnSaveClicked(object sender, EventArgs e)

        {

            var todoItem = (TodoItem)BindingContext;

            TodoRepository database = TodoRepository.Instance;

            database.SaveItem(todoItem);

            await Navigation.PopAsync();

        }

        async void OnDeleteClicked(object sender, EventArgs e)

        {

            var todoItem = (TodoItem)BindingContext;

            TodoRepository database = TodoRepository.Instance;

            database.DeleteItem(todoItem);

            await Navigation.PopAsync();

        }

        async void OnCancelClicked(object sender, EventArgs e)

        {

            await Navigation.PopAsync();

        }

    }

}

Creating the Todo List Page

The Todo List Page is responsible for listing all to-do items in the application You are going to create Todo List Page by carrying out the following steps:

  1. Create a content page called TodoListPage by right clicking the Views folder, click Add, and click New Item. This will display the Add New Item
  2. In the Add New Item dialog, click Forms, and then Content Page. Enter TodoListPage in the field Name and click on the button Add.
  3. Follow the steps described in the section Migrating to .NET MAUI Content Page to migrate the TodoListPage to .NET MAUI.
  4. Double-click the TodoListPage.xaml file and replace update the Xaml with the following markup:

<?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="TodoMAUI.Views.TodoListPage" Title="Todo">

        <ContentPage.ToolbarItems>

            <ToolbarItem Text="+" Clicked="OnItemAdded">

                <ToolbarItem.IconImageSource>

                    <OnPlatform x:TypeArguments="ImageSource">

                        <On Platform="Android, UWP" Value="plus.png" />

                    </OnPlatform>

                </ToolbarItem.IconImageSource>

            </ToolbarItem>

        </ContentPage.ToolbarItems>

        <ListView x:Name="listView"

              Margin="20"

              ItemSelected="OnListItemSelected">

            <ListView.ItemTemplate>

                <DataTemplate>

                    <ViewCell>

                        <StackLayout Margin="20,0,0,0" Orientation="Horizontal" HorizontalOptions="FillAndExpand">

                            <Label Text="{Binding Name}" VerticalTextAlignment="Center" HorizontalOptions="StartAndExpand" />

                            <Image Source="check.png" HorizontalOptions="End" IsVisible="{Binding Done}" />

                        </StackLayout>

                    </ViewCell>

                </DataTemplate>

            </ListView.ItemTemplate>

        </ListView>

</ContentPage>

  1. Add the images png, check2x.png, and plus.png to the folder Resources/Images. Ensure the Build Action of each image is MAUIImage:

Figure 16 – Adding Images to Resources/Images folder

  1. Double-click the TodoListPage.xaml.cs file and update the existing code with the following:

using Microsoft.MAUI.Controls;

using TodoMAUI.Models;

using TodoMAUI.Repositories;

namespace TodoMAUI.Views

{

    public partial class TodoListPage : ContentPage

    {

        public TodoListPage()

        {

            InitializeComponent();

        }

        protected override async void OnAppearing()

        {

            base.OnAppearing();

 

            TodoRepository database = TodoRepository.Instance;

            listView.ItemsSource = database.GetItems();

        }

 

        async void OnItemAdded(object sender, EventArgs e)

        {

            await Navigation.PushAsync(new TodoItemPage

            {

                BindingContext = new TodoItem()

            });

        }

 

        async void OnListItemSelected(object sender, SelectedItemChangedEventArgs e)

        {

            if (e.SelectedItem != null)

            {

                await Navigation.PushAsync(new TodoItemPage

                {

                    BindingContext = e.SelectedItem as TodoItem

                });

            }

        }

    }

}

Updating the initial UI page for the app

Next, you are going to update the App class to show the Todo List Page as the first page when the app opens. App is the main class of a MAUI application that manages the lifecycle. It is responsible, among other things, for setting the initial UI page for the app.

  1. First, add some styles at the application level. Open the App.xaml file and update the Xaml markup with the following:

<Application xmlns="http://schemas.microsoft.com/dotnet/2021/MAUI" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:windows="clr-namespace:Microsoft.MAUI.Controls.PlatformConfiguration.WindowsSpecific;assembly=Microsoft.MAUI.Controls" xmlns:local="clr-namespace:TodoMAUI" x:Class="TodoMAUI.App"              windows:Application.ImageDirectory="Assets">

    <Application.Resources>

        <ResourceDictionary>

            <Color x:Key="primaryGreen">#91CA47</Color>

            <Color x:Key="primaryDarkGreen">#6FA22E</Color>

        </ResourceDictionary>

    </Application.Resources>

</Application>

  1. Open the App.xaml.cs file and modify the constructor by setting MainPage to a new instance of TodoListPage:

public App()

{

    InitializeComponent();

    MainPage = new NavigationPage(new TodoListPage())

    {

        BarTextColor = Color.FromArgb("#FFFFFF"),

        BarBackgroundColor = Color.FromArgb(App.Current.Resources["primaryGreen"].ToString())

    };

}

Running the to-do list app

Make sure that you have installed the minimum SDK for the corresponding target platform you want to test the to-do list app on. .NET MAUI supports the following minimum platform configuration:

  • Android 5.0 (API 21) or higher.
  • iOS 10 or higher.
  • macOS 10.13 or higher.
  • Windows desktop and the Universal Windows Platform (UWP), using Windows UI Library (WinUI) 3.

In this article, we have tested the to-do list app using Pixel 3a Q 10.0 – API 29 (Android 10.0 – API 20) and Pixel XL Pie 9.0 – API 28 (Android 9.0 – API 28) Android emulators.

Now, in Visual Studio, select a target platform and run the application.

Figure 17 – Running the to-do list app on an Android Emulator

Troubleshooting

This last section is intended to support you during the process of installing .NET MAUI and building the to-do list app. These are the issues we incurred while writing this article. This is not intended to be an extensive list of errors you might encounter while reading this article and building the to-do list app.

The build was cancelled because another Xamarin operation is running

When building the solution, the Setup Hot Restart window shows up and after closing it, the build stops with the following message in the Output window:

Build started...

The build was cancelled because another Xamarin operation is running. Please try again in a moment.

1>Error: Cancelled

The Setup Hot Restart window enabled you to deploy the application to a local iOS device. If you do not have a local iOS device, then change the target device from Local Device to an android emulator in the Visual Studio toolbar and try building again:

Figure 18 – Changing the target device to Android Emulator

Building with JDK version `(version number)` is not supported

Carry out the following steps:

  1. Check if OpenJDK is installed on the machine in the correct location:

Mac – $HOME/Library/Developer/Xamarin/jdk/microsoft_dist_openjdk_1.8.0.x

Windows – C:\Program Files\Android\jdk\microsoft_dist_openjdk_1.8.0.x

  1. Point the IDE to the new JDK:

Mac – Click Tools > SDK Manager > Locations and change the Java SDK (JDK) Location to the full path of the OpenJDK installation. In the following example, this path is set to $HOME/Library/Developer/Xamarin/jdk/microsoft_dist_openjdk_1.8.0.9 but your version may be newer.

Figure 19 – Updating the JDK location on Visual Studio for Mac

Windows: Click Tools > Options > Xamarin > Android Settings and change the Java Development Kit location to the full path of the OpenJDK installation. In the following example, this path is set to C:\Program Files\Android\jdk\microsoft_dist_openjdk_1.8.0.9, but your version may be newer:

Figure 20 – Updating the JDK location on Visual Studio for Windows

For more information, see Microsoft’s documentation on Mobile OpenJDK Distribution – Xamarin.

Could not resolve type with token 01000008

When attempting to run the app on an Emulator, you might get the following exception from the Visual Studio:

[mono-rt] [ERROR] FATAL UNHANDLED EXCEPTION: System.TypeLoadException: Could not resolve type with token 01000008 from typeref (expected class 'System.Drawing.BitmapSuffixInSatelliteAssemblyAttribute' in assembly 'System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')

This is a known issue and have been reported recently – [XAML Hot Reload] System.TypeLoadException – Visual Studio Feedback.

As a workaround, try:

  • Uninstalling the application from the emulator and then deploy and run the application from Visual Studio again.
  • Disabling the XAML Hot Reload. It can be disabled by unchecking the Enable Xamarin Hot Reload checkbox at Tools > Options > Xamarin > Hot Reload.

Missing iOS workload

While attempting to run a dotnet-restore command line, you might encounter the following error message: Missing iOS workload.

This can happen when Visual Studio 2022 Preview is updated along with the .NET 6 Preview, but the .NET MAUI workload is not updated together with them.

Figure 21 – dotnet restore command failing with the missing iOS workload message

Run the following .NET CLI commands to update .NET MAUI workload and check for missing updates:

dotnet tool update -g redth.net.MAUI.check

Finally, run the following command to check your development environment:

maui-check

If any tools and SDKs required by .NET MAUI are missing, maui-check will prompt you to install them.

Inadequate permissions to access, please elevate to run this command

Always run the command prompt or terminal as an Administrator (or sudo) when executing .NET CLI commands to install/update .NET MAUI.

Figure 22 – .NET CLI command outputs inadequate permissions message

Summary

In this article, you learned how to install .NET MAUI and its prerequisites as well as check if anything is missing from the installation by using the .NET CLI command maui-check. To demonstrate the simplicity of implementing .NET MAUI in comparison to its antecessor Xamarin.Forms, we compared the project structure between the two frameworks. Then, finally you built and run your first .NET MAUI application.

With the new skills learned in this article, you can build simple cross-platform apps using .NET MAUI and start migrating existing Xamarin.Forms projects.

By | 2021-09-14T06:36:26+00:00 August 27th, 2021|Uncategorized|0 Comments

About the Author:

Leave A Comment