How to toggle the light and dark themes for Syncfusion controls in .NET MAUI?
Implementing theme switching in a .NET MAUI application enhances the user experience by allowing users to toggle between light and dark themes. Here’s how you can implement theme switching for the Syncfusion® controls using SyncfusionThemeResourceDictionary.
App.xaml Configuration
Ensure that your App.xaml includes the SyncfusionThemeResourceDictionary
:
<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:SyncfusionThemeSample"
xmlns:themes="clr-namespace:Syncfusion.Maui.Themes;assembly=Syncfusion.Maui.Core"
x:Class="SyncfusionThemeSample.App">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<themes:SyncfusionThemeResourceDictionary VisualTheme="MaterialLight"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
XAML
Define the layout and Syncfusion controls
in your XAML file. Here we have defined the SfButton control:
<StackLayout>
<buttons:SfButton Text="Change Theme (Light/ Dark)"
HorizontalOptions="Center"
VerticalOptions="Center"
Clicked="ChangeSyncfusionControlsTheme"/>
</StackLayout>
C#
Utilize the button-click event to toggle the light and dark themes.
private void ChangeSyncfusionControlsTheme(object sender, EventArgs e)
{
ICollection<ResourceDictionary> mergedDictionaries = Application.Current.Resources.MergedDictionaries;
if (mergedDictionaries != null)
{
var theme = mergedDictionaries.OfType<SyncfusionThemeResourceDictionary>().FirstOrDefault();
if (theme != null)
{
if (theme.VisualTheme is SfVisuals.MaterialDark)
{
theme.VisualTheme = SfVisuals.MaterialLight;
Application.Current.UserAppTheme = AppTheme.Light;
}
else
{
theme.VisualTheme = SfVisuals.MaterialDark;
Application.Current.UserAppTheme = AppTheme.Dark;
}
}
}
}
By following these steps, you can successfully implement a theme switcher in your .NET MAUI application using SyncfusionThemeResourceDictionary
. This allows for a dynamic and customizable user interface that can adapt to the user’s preferences.
Output
Download the complete sample on GitHub