.Net Maui Platform Specific Styling Lightdark Theme Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    7 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of .NET MAUI Platform Specific Styling Light,Dark Theme

.NET MAUI Platform Specific Styling for Light and Dark Themes

Understanding Themes in .NET MAUI

.NET MAUI provides a robust theming system that allows developers to apply a light or dark theme to their application. These themes can be set at the application level or even at a more granular level, such as individual pages or controls. The application can dynamically switch between themes based on user preferences or system settings.

Platform-Specific Styling

While .NET MAUI abstracts many platform-specific details, there are times when platform-specific styling is required for a better integration and user experience. Below are the steps and important information needed to implement platform-specific styling for light and dark themes in .NET MAUI.

Step-by-Step Guide

  1. Defining Styles in XAML:

    Create styles in XAML for both light and dark themes. You can define these styles in resource dictionaries and then apply them according to the theme. For example:

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <!-- Light theme styles -->
                <ResourceDictionary x:Name="LightTheme">
                    <Color x:Key="TextColor">#000</Color>
                    <Color x:Key="BackgroundColor">#FFF</Color>
                </ResourceDictionary>
    
                <!-- Dark theme styles -->
                <ResourceDictionary x:Name="DarkTheme">
                    <Color x:Key="TextColor">#FFF</Color>
                    <Color x:Key="BackgroundColor">#000</Color>
                </ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
    
  2. Detecting the Current Theme:

    .NET MAUI automatically detects the current theme on the device. However, if you need to programmatically handle theme changes, you can subscribe to the RequestedThemeChanged event:

    protected override void OnCreate()
    {
        base.OnCreate();
        this.RequestedThemeChanged += OnAppThemeChanged;
    }
    
    private void OnAppThemeChanged(object sender, AppThemeChangedEventArgs e)
    {
        ApplyTheme(e.RequestedTheme);
    }
    
  3. Applying Styles Based on Theme:

    Use a method to apply the correct styles based on the current theme:

    public void ApplyTheme(AppTheme theme)
    {
        ResourceDictionary themeResourceDictionary = null;
    
        switch (theme)
        {
            case AppTheme.Light:
                themeResourceDictionary = Application.Current.Resources.MergedDictionaries.FirstOrDefault(d => d[x:Name] == "LightTheme");
                break;
            case AppTheme.Dark:
                themeResourceDictionary = Application.Current.Resources.MergedDictionaries.FirstOrDefault(d => d[x:Name] == "DarkTheme");
                break;
        }
    
        if (themeResourceDictionary != null)
        {
            Application.Current.Resources.MergedDictionaries.Clear();
            Application.Current.Resources.MergedDictionaries.Add(themeResourceDictionary);
        }
    }
    

Platform-Specific Customizations

While the above steps cover general theme handling, sometimes platform-specific customizations are necessary. Here are some platform-specific considerations:

  1. iOS:

    iOS natively supports dynamic type and dark mode, so .NET MAUI's theming system should work seamlessly. However, you can customize iOS-specific styles using Effects or Handlers.

  2. Android:

    Android also supports dark mode, but you may need to customize certain elements using Android-specific styles or themes. .NET MAUI's theming system automatically handles many of these cases, but customizations can be done by accessing the underlying Android views via Handler.

  3. Windows:

    Windows has strong support for dark mode, including system-level themes. Customizations can be done using platform-specific resources or styles in the App.xaml file.

Conclusion

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement .NET MAUI Platform Specific Styling Light,Dark Theme

Step 1: Create a .NET MAUI Project

If you haven’t already created a .NET MAUI project, you can do so by following these steps:

  • Open Visual Studio.
  • Create a new project.
  • Select “.NET MAUI App” and click “Next.”
  • Configure your project by entering a name, location, and solution name, then click “Create.”
  • In the next window, you can choose which platforms you want to target. Click “Create” to proceed.

Step 2: Define Themes

.NET MAUI allows you to define styles in XAML that can be applied conditionally based on the theme (light or dark).

  1. Open App.xaml and add resource dictionaries for light and dark themes:
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiAppTheme.App">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <!-- Default light theme styles -->
                <ResourceDictionary Source="Resources/Styles/LightThemeStyles.xaml" />
                <!-- Default dark theme styles -->
                <ResourceDictionary Source="Resources/Styles/DarkThemeStyles.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Step 3: Create Style Files

  1. Create two .xaml files for light and dark themes in Resources/Styles.
  • Right-click on Resources/Styles folder, select Add > New Item, then choose Resource Dictionary (.xaml).
  • Name the first file LightThemeStyles.xaml and the second DarkThemeStyles.xaml.
  1. Define some styles in each file. Here’s an example:

LightThemeStyles.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
    <!-- Light theme-specific styles -->
    <Color x:Key="PrimaryColor">#3498db</Color>
    <Color x:Key="BackgroundColor">#ecf0f1</Color>
    <Color x:Key="TextColor">#2c3e50</Color>
    <Style x:Key="BaseStyle" TargetType="ContentView">
        <Setter Property="BackgroundColor" Value="{StaticResource BackgroundColor}" />
    </Style>
</ResourceDictionary>

DarkThemeStyles.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
    <!-- Dark theme-specific styles -->
    <Color x:Key="PrimaryColor">#27ae60</Color>
    <Color x:Key="BackgroundColor">#34495e</Color>
    <Color x:Key="TextColor">#ecf0f1</Color>
    <Style x:Key="BaseStyle" TargetType="ContentView">
        <Setter Property="BackgroundColor" Value="{StaticResource BackgroundColor}" />
    </Style>
</ResourceDictionary>

Step 4: Apply Styles Based on Theme

  1. Use the defined styles in your pages. Here’s an example MainPage.xaml:
<?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="MauiAppTheme.MainPage"
             Style="{StaticResource BaseStyle}">
    <ContentPage.Content>
        <StackLayout VerticalOptions="Center">
            <Label Text="Hello, .NET MAUI!"
                   TextColor="{StaticResource TextColor}"
                   SemanticProperties.Hint="Welcome to .NET MAUI"
                   FontSize="18" />
            <Button x:Name="ToggleThemeButton"
                    Text="Toggle Theme"
                    Clicked="ToggleThemeButton_Clicked"
                    TextColor="{StaticResource TextColor}" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Step 5: Toggle Theme Programmatically (Optional)

  1. Add a button click event handler in MainPage.xaml.cs to toggle between light and dark themes:
using Microsoft.Maui.Controls;

namespace MauiAppTheme
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void ToggleThemeButton_Clicked(object sender, EventArgs e)
        {
            if (Application.Current.UserAppTheme == AppTheme.Light)
            {
                Application.Current.UserAppTheme = AppTheme.Dark;
            }
            else
            {
                Application.Current.UserAppTheme = AppTheme.Light;
            }
        }
    }
}

Step 6: Set Default Theme (Optional)

  1. Optionally, set the default theme in App.xaml.cs:
using Microsoft.Maui.Controls;

namespace MauiAppTheme
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();

            // Set default theme to Light
            Application.Current.UserAppTheme = AppTheme.Light;

            MainPage = new MainPage();
        }
    }
}

Conclusion

You have now set up basic platform-specific styling for light and dark themes in a .NET MAUI application. This example demonstrates how to define, apply, and toggle themes using XAML and C#. You can expand on this by adding more styles and controls to your application.

Top 10 Interview Questions & Answers on .NET MAUI Platform Specific Styling Light,Dark Theme

1. How do I implement Light and Dark themes in .NET MAUI?

Answer: .NET MAUI allows you to define different styles for Light and Dark themes by utilizing Resource Dictionaries. You can create separate XAML files for each theme, like LightTheme.xaml and DarkTheme.xaml, and then apply the appropriate theme based on the system settings. You can switch themes programmatically in your application if needed.

2. Can I automatically switch themes when the system theme changes?

Answer: Yes, .NET MAUI automatically switches between Light and Dark themes based on the system settings. You can use the Application.RequestedThemeChanged event to handle changes to the system theme and perform any additional actions if necessary.

3. How do I define platform-specific styles in .NET MAUI?

Answer: You can define platform-specific styles by using the platform-specific resource qualifiers, like LightTheme.xaml for Light theme and DarkTheme.xaml for Dark theme. Additionally, you can use the OnPlatform markup extension for XAML or the Device.RuntimePlatform API in code-behind to apply platform-specific styles.

4. How do I use styles from Resource Dictionaries in .NET MAUI?

Answer: To use styles from Resource Dictionaries, you first need to merge the appropriate Resource Dictionary based on the current theme. For example, in your App.xaml, you can conditionally merge LightTheme.xaml or DarkTheme.xaml. Then, you can reference these styles in your XAML controls using the Style property.

<Style TargetType="Button" x:Key="MyButtonStyle">
    <Setter Property="TextColor" Value="{AppThemeBinding Light=Black, Dark=White}" />
</Style>

5. Can I use CSS for theming in .NET MAUI?

Answer: Yes, .NET MAUI supports using CSS for styling, which can be especially useful for theming. You can define CSS files for each theme and then apply them similarly to Resource Dictionaries. Use Application.LoadFromCSS to load the CSS file based on the current theme.

6. How do I test themes on different platforms in .NET MAUI?

Answer: You can test themes on different platforms using emulators and simulators for iOS and Android, as well as Windows and macOS platforms. Ensure you manually switch the system theme on each platform to verify how your app responds. You can also use the OnPlatform markup extension to define platform-specific styles and test them accordingly.

7. Can I create a custom theme in .NET MAUI?

Answer: Absolutely! You can create a custom theme by defining a new Resource Dictionary with your custom styles and colors. You can then apply this custom theme in your app by merging it in the App.xaml file or programmatically as needed.

8. How do I handle theme changes in code-behind?

Answer: You can handle theme changes in code-behind by subscribing to the Application.RequestedThemeChanged event. In the event handler, you can update your UI and styles as required to reflect the new theme.

public App()
{
    InitializeComponent();
    RequestedThemeChanged += App_RequestedThemeChanged;
}

private void App_RequestedThemeChanged(object sender, AppThemeChangedEventArgs e)
{
    if (e.RequestedTheme == AppTheme.Dark)
    {
        // Apply dark theme styles
    }
    else
    {
        // Apply light theme styles
    }
}

9. How do I make sure my UI looks good in both Light and Dark themes?

Answer: To ensure your UI looks good in both themes, pay close attention to color contrast and choose colors wisely to meet accessibility guidelines. Use AppThemeBinding in your styles to define how properties change based on the theme. Test your UI on different devices and screen sizes in both modes to catch any issues early.

10. What are the best practices for theming in .NET MAUI?

Answer: Best practices for theming in .NET MAUI include:

  • Use Resource Dictionaries for centralized management of styles.
  • Leverage AppThemeBinding to apply different properties based on the theme.
  • Test your app’s themes on all target platforms.
  • Ensure color contrast meets accessibility standards.
  • Keep your styles DRY (Don't Repeat Yourself) by reusing styles where possible.

You May Like This Related .NET Topic

Login to post a comment.