.NET MAUI: Implementing Light and Dark Modes

In modern application development, providing users with the ability to switch between light and dark modes has become an essential feature. This functionality not only enhances user experience but also accommodates personal preferences and improves accessibility. In this blog post, we will explore how to implement light and dark modes in .NET MAUI apps using the UserAppTheme property in the App.xaml.cs file.

Understanding the App.xaml.cs File

The App.xaml.cs file in a .NET MAUI application is responsible for defining the application’s startup and initialization logic. It acts as the entry point for the application and provides a central location to handle events and configure application-wide settings.

Setting the UserAppTheme Property

To enable light and dark modes in your .NET MAUI app, you need to access the UserAppTheme property available in the Application.Current object. This property allows you to specify the desired theme for your application.

If your application does not allow the users to change the light/dark modes, but you want to force the app to be in a specified state, you can use the App.xaml.cs constructor, and you can set the UserAppTheme property to either AppTheme.Light or AppTheme.Dark, depending on a predefined default.

Here’s an example of how to set the AppTheme to Light mode:

Application.Current.UserAppTheme = AppTheme.Light;

Similarly, you can set the AppTheme to Dark mode:

Application.Current.UserAppTheme = AppTheme.Dark;
This content has 11 months. Some of the information in this post may be out of date or no longer work. Please, read this page keeping its age in your mind.