Building Cross-Platform Applications with .NET MAUI
Introduction
.NET Multi-platform App UI (.NET MAUI) is a cross-platform framework for creating native mobile and desktop apps with C# and .NET. It is the evolution of Xamarin.Forms and allows developers to build applications for iOS, Android, macOS, and Windows with a single codebase.
Setting Up .NET MAUI
To get started with .NET MAUI, you need to install Visual Studio 2022 or later with the .NET MAUI workload.
Installation Steps
// Step 1: Download and install Visual Studio 2022
// Step 2: Select the '.NET MAUI' workload during installation
// Step 3: Create a new .NET MAUI App project
Creating Your First .NET MAUI Project
Let's create a simple .NET MAUI project that displays a "Hello, World!" message.
Example Project Structure
- MyMauiApp
- MyMauiApp.Android
- MyMauiApp.iOS
- MyMauiApp.MacCatalyst
- MyMauiApp.Windows
- MyMauiApp
- App.xaml
- MainPage.xaml
- MainPage.xaml.cs
Building the User Interface
The UI in .NET MAUI is built using XAML. Here is how you can create a simple UI.
MainPage.xaml
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyMauiApp.MainPage">
<VerticalStackLayout>
<Label Text="Hello, World!"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
</VerticalStackLayout>
</ContentPage>
Adding Functionality
Let's add a button to the UI and handle its click event in the code-behind.
MainPage.xaml
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyMauiApp.MainPage">
<VerticalStackLayout>
<Label x:Name="helloLabel" Text="Hello, World!"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
<Button Text="Click Me"
Clicked="OnButtonClicked" />
</VerticalStackLayout>
</ContentPage>
MainPage.xaml.cs
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void OnButtonClicked(object sender, EventArgs e)
{
helloLabel.Text = "Hello, .NET MAUI!";
}
}
Running the Application
You can run the application on an Android emulator, iOS simulator, Windows, or macOS.
Running on Android Emulator
// Step 1: Start the Android emulator from Visual Studio
// Step 2: Select the Android project as the startup project
// Step 3: Click the 'Run' button