Friday, 1 August 2025

Theme in MAUI

 .NET MAUI (Multi-platform App UI), themes allow you to define consistent styling (colors, fonts, and other UI properties) across your application for light and dark modes or custom themes.

πŸ’‘ What Is a Theme in MAUI?

A theme in MAUI is typically a collection of ResourceDictionaries (colors, styles, etc.) that can be applied globally or per page. Themes support light and dark modes automatically, and you can also create your own custom themes.


πŸ”§ Basic Theme Setup in MAUI

1. App.xaml

Define your base styles and resources:


<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui" x:Class="YourApp.App"> <Application.Resources> <ResourceDictionary> <Color x:Key="PrimaryColor">#512BD4</Color> <Style TargetType="Label"> <Setter Property="TextColor" Value="{DynamicResource PrimaryColor}" /> </Style> </ResourceDictionary> </Application.Resources> </Application>

2. Light and Dark Theme Resource Files

Resources/Styles/ColorsLight.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui"> <Color x:Key="PrimaryColor">#512BD4</Color> <Color x:Key="BackgroundColor">#FFFFFF</Color> </ResourceDictionary>
Resources/Styles/ColorsDark.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui"> <Color x:Key="PrimaryColor">#BB86FC</Color> <Color x:Key="BackgroundColor">#121212</Color> </ResourceDictionary>

3. Load Themes Based on System Settings

In App.xaml.cs:

public App() { InitializeComponent(); if (Application.Current.RequestedTheme == AppTheme.Dark) { Resources.MergedDictionaries.Add(new ColorsDark()); } else { Resources.MergedDictionaries.Add(new ColorsLight()); } MainPage = new AppShell(); // or any page }

🎯 Tips for Working with Themes

  • Use DynamicResource instead of StaticResource for runtime theme switching.

  • MAUI supports App Theme Binding, which automatically changes resources when the system theme changes.

  • You can define multiple themes and switch them manually if needed.


πŸŒ™ Theme Switching Example

To switch themes manually at runtime:

void SwitchToDarkTheme() { Application.Current.Resources.MergedDictionaries.Clear(); Application.Current.Resources.MergedDictionaries.Add(new ColorsDark()); }

No comments:

Post a Comment

Cricket Streaming MAUI App: Complete Solution

This document outlines a comprehensive solution for building a cricket streaming MAUI app with subscription plans, geo-restrictions, and pre...

Ads2