MAUI Platform-Specifics

In .NET MAUI, platform-specifics allow you to access native APIs and customize the UI and behavior of your application on a per-platform basis. This is crucial for taking full advantage of each operating system's unique features.

Why Use Platform-Specifics?

Methods for Implementing Platform-Specifics

1. `OnPlatform` Markup Extension

The `OnPlatform` markup extension is a convenient way to set property values on controls differently for each platform. It's ideal for styling and simple value differences.

<Button Text="Click Me"
                    BackgroundColor="{OnPlatform iOS={StaticResource ButtoniOSBackground}, Android={StaticResource ButtonAndroidBackground}}"
                    TextColor="{OnPlatform WinUI=White, Default=Black}" />

You can also use the generic version:

<Label Text="Hello World"
                    FontSize="{OnPlatform<double>(iOS: 20, Android: 24, Default: 18)}" />

2. `OnIdiom` Markup Extension

Similar to `OnPlatform`, `OnIdiom` allows you to set property values based on the device's idiom (Phone, Tablet, Desktop, TV).

<StackLayout Padding="{OnIdiom<Thickness>(Phone: 10, Tablet: 20, Desktop: 50)}">
        <!-- Content -->
    </StackLayout>

3. Conditional Compilation

Use preprocessor directives to conditionally compile code blocks for specific platforms. This is useful for implementing entire methods or classes that are platform-specific.

public static class DeviceInfo
{
#if IOS
    public static string GetPlatformName() => "iOS";
#elif ANDROID
    public static string GetPlatformName() => "Android";
#elif WINDOWS
    public static string GetPlatformName() => "Windows";
#elif MACCATALYST
    public static string GetPlatformName() => "Mac Catalyst";
#else
    public static string GetPlatformName() => "Unknown";
#endif
}

4. Dependency Service (for deeper platform integration)

For more complex platform-specific implementations, you can use a Dependency Service. This involves defining an interface in your shared MAUI code and then providing platform-specific implementations of that interface.

Step 1: Define the Interface (Shared Code)

namespace MyMauiApp.Services
{
    public interface IPlatformSpecificService
    {
        string GetNativeMessage();
    }
}

Step 2: Implement the Interface (Platform-Specific Projects)

iOS Project:

using Foundation;
using MyMauiApp.Services;

namespace MyMauiApp.iOS
{
    public class PlatformSpecificService : IPlatformSpecificService
    {
        public string GetNativeMessage()
        {
            return "Hello from iOS native code!";
        }
    }
}

Android Project:

using Android.OS;
using MyMauiApp.Services;

namespace MyMauiApp.Android
{
    public class PlatformSpecificService : IPlatformSpecificService
    {
        public string GetNativeMessage()
        {
            return "Hello from Android native code!";
        }
    }
}

Step 3: Register and Resolve the Dependency

In your MauiProgram.cs:

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            });

        // Register platform-specific services
        builder.Services.AddTransient<IPlatformSpecificService, PlatformSpecificService>(); // This will automatically pick the correct platform implementation

        return builder.Build();
    }
}

Step 4: Use the Service in Shared Code

using MyMauiApp.Services;

public partial class MainPage : ContentPage
{
    private readonly IPlatformSpecificService _platformService;

    public MainPage(IPlatformSpecificService platformService)
    {
        InitializeComponent();
        _platformService = platformService;
        DisplayAlert("Native Message", _platformService.GetNativeMessage(), "OK");
    }
}

Platform-Specific UI

You can also apply platform-specific styles or handlers directly to controls.

Handler Customization

MAUI uses handlers to bridge the gap between the cross-platform control and the native control. You can customize these handlers for platform-specific behavior or appearance. This is a more advanced topic often covered in dedicated handler customization guides.

Note: When using platform-specific code, always strive for a balance. Excessive platform-specific code can reduce code sharing and increase maintenance overhead. Use it judiciously for features that truly require it.
Tip: For simpler property differences, `OnPlatform` and `OnIdiom` are generally preferred over conditional compilation or dependency services.
Important: Ensure your platform-specific implementations correctly handle lifecycle events and resource management relevant to each platform.

Explore the official .NET MAUI documentation for detailed examples and best practices on implementing platform-specifics for each target OS.

Go to Top