.NET MAUI – One Codebase, Multiple Platforms

.NET MAUI – One Codebase, Multiple Platforms

.NET developers now have a first-class cross-platform UI stack for Android, iOS, macOS, and Windows

Last updated 5/26/2022 9:19 PM
gui.h
14 min read
Category
MAUI
Tags
.NET C# MAUI

Welcome to .NET Multi-platform App UI. This release marks a new milestone in our multi-year journey to unify the .NET platform. Now, you and over 5 million other .NET developers have a first-class cross-platform UI stack for Android, iOS, macOS, and Windows that complements the .NET toolchain (SDK) and base class library (BCL). You can build anything with .NET.

Join us at Microsoft Build 2022 where we will share all the updates for building native apps for any device using .NET and Visual Studio. » Learn more.

This is just the beginning of our journey to create a desktop and mobile app experience that satisfies .NET developers. For the next phase, the foundation has now been laid for the broader .NET ecosystem, introducing plugins, libraries, and services from .NET Framework and legacy project systems into .NET 6 and SDK-style projects. Currently available products include:

Below are some screenshot links. Due to the large number of links, screenshots are provided directly. If interested, click the original article to view:

For help migrating libraries to .NET 6, check out recent guest blog posts from Michael Rumpler (MR.Gestures) and Luis Matos (Plugin.ValidationRules).

Under the 18-month current release plan, the .NET MAUI workload is fully supported and will be serviced on the same monthly cadence as .NET. Our continuing focus for .NET MAUI remains quality, addressing known issues and prioritizing issues based on your feedback. This also includes the workloads we provide for building apps specifically targeting Android, Android Wear, CarPlay, iOS, macOS, and tvOS, using .NET's native toolkits directly, along with support libraries for AndroidX, Facebook, Firebase, Google Play Services, and SkiaSharp.

With .NET MAUI, you can deliver uncompromised user experiences while sharing more code than ever before. .NET MAUI uses native UI through the top-tier app toolkits provided by each platform, modern developer productivity, and our fastest mobile platform to date.

Native UI, No Compromises

The primary goal of .NET MAUI is to enable you to deliver the best app experience tailored for each platform (Android, iOS, macOS, and Windows), while also allowing you to create a consistent brand experience through rich styling and graphics. Out of the box, each platform looks and behaves as it should, without the need for additional widgets or styles to emulate. For example, .NET MAUI on Windows is powered by WinUI 3, the premier native UI component shipped with the Windows App SDK.

Build apps using C# and XAML from a rich toolkit containing over 40 controls, layouts, and pages. Building on the shoulders of Xamarin for mobile controls, .NET MAUI adds support for multi-window desktop applications, menu bars, and new animation capabilities, borders, corners, shadows, graphics, and more. Oh, and there's the new feature I'll highlight below: BlazorWebView.

Read more about controls in the .NET MAUI documentation: Pages, Layouts, and Views.

Accessibility First

A major advantage of using native UI is the inherited accessibility support, which we build upon with semantic services to make creating highly accessible applications easier than ever. We have worked closely with customers to redesign our approach to accessibility development. Through these conversations, we designed the .NET MAUI Semantic Services to control:

  • Properties such as descriptions, hints, and heading levels
  • Focus
  • Screen readers
  • Automation properties

Read more about accessibility semantic services in the .NET MAUI documentation.

Beyond the User Interface

.NET MAUI provides simple APIs to access services and features on each platform, such as accelerometer, app actions, file system, notifications, and more. In this example, we configure app actions to add menu options to the app icon on each platform:

AppActions.SetAsync(
    new AppAction("current_info", "Check Current Weather", icon: "current_info"),
    new AppAction("add_location", "Add a Location", icon: "add_location")
);

Read more about accessing platform services and features in the .NET MAUI documentation.

Easy Customization

Whether you're extending the functionality of a .NET MAUI control or creating new platform features, .NET MAUI is designed for extensibility, so you never hit a wall. Take the Entry control as an example, which is a typical control rendered differently on each platform. Android draws an underline below the text field, and developers often want to remove it. With .NET MAUI, you can customize everything across the entire project with just a few lines of code:

#if ANDROID
Microsoft.Maui.Handlers.EntryHandler.Mapper.ModifyMapping("NoUnderline", (h, v) =>
{
    h.PlatformView.BackgroundTintList = ColorStateList.ValueOf(Colors.Transparent.ToPlatform());
});
#endif

Here's a great example from Cayas Software recently creating a new custom Map platform control. This blog post demonstrates creating a handler for the control, implementing it on each platform, and then making it available by registering the control in .NET MAUI.

.ConfigureMauiHandlers(handlers =>
{
    handlers.AddHandler(typeof(MapHandlerDemo.Maps.Map),typeof(MapHandler));
})

Read more about customizing controls with handlers in the .NET MAUI documentation.

Modern Developer Productivity

As a technology that can build anything, we want .NET to also enhance your productivity through common language features, patterns, practices, and tooling.

.NET MAUI uses new C# 10 features introduced in .NET 6, including global using directives and file-scoped namespaces, which are great for reducing clutter and mess in files. .NET MAUI takes multi-targeting to a new level, allowing us to focus on "single project".

In a new .NET MAUI project, platform files reside in a subfolder, keeping the focus on the application where you spend most of your effort. In the project's "Resources" folder, you can manage your app's fonts, images, app icons, splash screens, raw resources, and styles from a single location. .NET MAUI will optimize these for the unique requirements of each platform.

Multi-project vs. Single project: Building your solution with separate projects for each platform is still supported, so you can choose when the single-project approach is right for your application.

.NET MAUI uses the popular builder pattern from Microsoft.Extensions libraries, also used in ASP.NET and Blazor applications, as a unified way to initialize and configure apps. Here, you can provide fonts to .NET MAUI, leverage platform-specific lifecycle events, configure dependencies, enable specific features, enable vendor control toolkits, and more.

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .ConfigureServices()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("Segoe-Ui-Bold.ttf", "SegoeUiBold");
                fonts.AddFont("Segoe-Ui-Regular.ttf", "SegoeUiRegular");
                fonts.AddFont("Segoe-Ui-Semibold.ttf", "SegoeUiSemibold");
                fonts.AddFont("Segoe-Ui-Semilight.ttf", "SegoeUiSemilight");
            });

        return builder.Build();
    }
}
public static class ServicesExtensions
{
    public static MauiAppBuilder ConfigureServices(this MauiAppBuilder builder)
    {
        builder.Services.AddMauiBlazorWebView();
        builder.Services.AddSingleton<SubscriptionsService>();
        builder.Services.AddSingleton<ShowsService>();
        builder.Services.AddSingleton<ListenLaterService>();
#if WINDOWS
        builder.Services.TryAddSingleton<SharedMauiLib.INativeAudioService, SharedMauiLib.Platforms.Windows.NativeAudioService>();
#elif ANDROID
        builder.Services.TryAddSingleton<SharedMauiLib.INativeAudioService, SharedMauiLib.Platforms.Android.NativeAudioService>();
#elif MACCATALYST
        builder.Services.TryAddSingleton<SharedMauiLib.INativeAudioService, SharedMauiLib.Platforms.MacCatalyst.NativeAudioService>();
        builder.Services.TryAddSingleton< Platforms.MacCatalyst.ConnectivityService>();
#elif IOS
        builder.Services.TryAddSingleton<SharedMauiLib.INativeAudioService, SharedMauiLib.Platforms.iOS.NativeAudioService>();
#endif

        builder.Services.TryAddTransient<WifiOptionsService>();
        builder.Services.TryAddSingleton<PlayerService>();

        builder.Services.AddScoped<ThemeInterop>();
        builder.Services.AddScoped<ClipboardInterop>();
        builder.Services.AddScoped<ListenTogetherHubClient>(_ =>
            new ListenTogetherHubClient(Config.ListenTogetherUrl));


        return builder;
    }
}

Read more in the .NET MAUI documentation: app startup with MauiProgram and single project.

Bringing Blazor to Desktop and Mobile

.NET MAUI is also great for web developers who want to engage through native client applications. .NET MAUI integrates with Blazor, so you can reuse existing Blazor web UI components directly in native mobile and desktop applications. With .NET MAUI and Blazor, you can reuse your web development skills to build cross-platform native client applications and create apps with consistent UI across mobile, desktop, and web.

.NET MAUI executes Blazor components natively on the device (no WebAssembly needed) and renders them into an embedded web view control. Since Blazor components compile and run in the .NET process, they are not limited to the web platform and can leverage any native platform features such as notifications, Bluetooth, geolocation, sensors, file system, and more. You can even add native UI controls alongside Blazor web UI. This is a brand new hybrid application: Blazor Hybrid!

Getting started with .NET MAUI and Blazor is simple: just use the included .NET MAUI Blazor App project template.

This template is fully set up so you can start building .NET MAUI Blazor apps using HTML, CSS, and C#. The Blazor Hybrid tutorial for .NET MAUI will guide you through building and running your first .NET MAUI Blazor app.

Alternatively, add a BlazorWebView control to an existing .NET MAUI app, wherever you want to start using Blazor components:

<BlazorWebView HostPage="wwwroot/index.html">
    <BlazorWebView.RootComponents>
        <RootComponent Selector="#app" ComponentType="{x:Type my:Counter}" />
    </BlazorWebView.RootComponents>
</BlazorWebView>

Blazor Hybrid support is also available for WPF and Windows Forms now, so you can start modernizing existing desktop applications to run on the web or cross-platform using .NET MAUI. The BlazorWebView control for WPF and WinForms is available on NuGet. Check out the Blazor Hybrid tutorials for WPF and WinForms to learn how to get started.

To learn more about Blazor Hybrid support for .NET MAUI, WPF, and Windows Forms, check out the Blazor Hybrid documentation.

Optimized for Speed

.NET MAUI is designed for performance. You told us how important it is to launch your apps as quickly as possible, especially on Android. The UI controls in .NET MAUI implement a streamlined, decoupled handler mapper pattern on native platform controls. This reduces the layers in UI rendering and simplifies control customization.

Layouts in .NET MAUI have been designed with a consistent manager pattern that optimizes measurement and arrangement loops for faster UI rendering and updates. In addition to StackLayout, we introduced layouts pre-optimized for specific scenarios, such as HorizontalStackLayout and VerticalStackLayout.

From the beginning of this journey, we set a goal to improve startup performance and maintain or reduce app size during the transition to .NET 6. At general availability, .NET MAUI improved by 34.9%, and .NET for Android improved by 39.4%. These gains extend to complex applications; the .NET Podcast sample application started with a startup time of 1299 ms, and at GA it runs at 814.2 ms, an improvement of 37.3% since Preview 13.

These settings are enabled by default for release builds to provide these optimizations.

Stay tuned for an in-depth blog post about the work we did to achieve these results.

Get Started Today

To get started with .NET MAUI on Windows, install Visual Studio 2022 Preview or update to version 17.3 Preview 1.1. In the installer, select the workload ".NET Multi-platform App UI development".

To use .NET MAUI on Mac, install the new Visual Studio 2022 Preview for Mac (17.3 Preview 1).

Visual Studio 2022 will ship .NET MAUI tooling support later this year. On Windows today, you can use XAML and .NET Hot Reload, along with powerful editors for XAML, C#, Razor, and CSS, to speed up your development loop. With XAML Live Preview and Live Visual Tree, you can preview, align, inspect, and edit your UI while debugging. The new single-project experience for .NET MAUI now includes project property pages to provide a visual editing experience for configuring your app with multi-platform targeting.

On Mac, you can now load single-project and multi-project .NET MAUI solutions and debug using the beautiful, brand new native Visual Studio 2022 for Mac experience. Additional features to boost productivity when developing .NET MAUI applications will be available in subsequent previews.

We recommend that you start updating your libraries to .NET MAUI and creating new .NET MAUI projects now. Before diving into migrating Xamarin projects to .NET MAUI, review dependencies, Visual Studio's support status for .NET MAUI, and published known issues to determine the right time for conversion. Remember, Xamarin will continue to be supported under the modern lifecycle policy, which states 2 years from the last major release.

Resources

We Need Your Feedback

We'd love to hear from you! When encountering any issues, please file a report on GitHub at dotnet/maui.

Summary

With .NET MAUI, you can build native apps for Android, iOS, macOS, and Windows from a single codebase, using the same productivity patterns you practice in .NET. .NET MAUI's streamlined and decoupled UI and layout architecture, along with the single project feature, allows you to focus on one app instead of juggling the unique requirements of multiple platforms. With .NET 6, we delivered performance improvements not only for Android but across all platform targets.

Less platform code, more shared code, consistent standards and patterns, lightweight and high-performance architecture, mobile and desktop native experiences – this is just the beginning. We look forward to seeing libraries and the broader ecosystem define a new era of cross-platform app development for .NET developers with .NET MAUI, enabling you and your organization to achieve more.

Try it now

Reprinted from the blog garden
Original author: https://www.cnblogs.com/springhgui/p/16304492.html
Original link: gui.h
Translation original address: https://devblogs.microsoft.com/dotnet/introducing-dotnet-maui-one-codebase-many-platforms/

Keep Exploring

Related Reading

More Articles