Skip to content

Latest commit

 

History

History
81 lines (66 loc) · 3.21 KB

File metadata and controls

81 lines (66 loc) · 3.21 KB

This article explains how to automatically switch .NET MAUI Syncfusion control themes based on the device-selected theme. This can be achieved by using SyncfusionThemeResourceDictionary.

To enable automatic theme switching for Syncfusion controls based on the device's selected theme in a .NET MAUI application, you can utilize the OnAppearing method to assign the Syncfusion VisualTheme. Additionally, handling the RequestedThemeChanged event allows for dynamic updates to the Syncfusion controls' theme when the device's theme changes at runtime.

App.xaml Configuration

Ensure that your App.xaml includes the SyncfusionThemeResourceDictionary:

<Application ...             
             xmlns:themes="clr-namespace:Syncfusion.Maui.Themes;assembly=Syncfusion.Maui.Core">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <themes:SyncfusionThemeResourceDictionary />
                ...
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

XAML

//Mainpage.xaml

<buttons:SfButton Text="Click me"/>

C#

  1. Override the OnAppearing method to apply the current theme and set up an event handler for theme changes.
  2. Implement the OnRequestedThemeChanged event handler to respond to theme changes during runtime.
  3. Define the ApplyTheme method to update the Syncfusion theme based on the current application theme.
//Mainpage.xaml.cs

protected override void OnAppearing()
{
    if (Application.Current != null)
    {
        this.ApplyTheme(Application.Current.RequestedTheme);
        Application.Current.RequestedThemeChanged += OnRequestedThemeChanged;
    }
    base.OnAppearing();
}

private void OnRequestedThemeChanged(object? sender, AppThemeChangedEventArgs e)
{
    this.ApplyTheme(e.RequestedTheme);
}

public void ApplyTheme(AppTheme appTheme)
{
    if (Application.Current != null)
    {
        ICollection<ResourceDictionary> mergedDictionaries = Application.Current.Resources.MergedDictionaries;
        if (mergedDictionaries != null)
        {
            var syncTheme = mergedDictionaries.OfType<SyncfusionThemeResourceDictionary>().FirstOrDefault();
            if (syncTheme != null)
            {
                if (appTheme is AppTheme.Light)
                {
                    syncTheme.VisualTheme = SfVisuals.MaterialLight;
                }
                else
                {
                    syncTheme.VisualTheme = SfVisuals.MaterialDark;
                }
            }
        }
    }
}

Output

Syncfusion_Theme.gif