Switching between Light and Dark mode without manual style

102 views Asked by At

I write an App with Xamarin.forms, and I want to change between light and dark mode. I want to have a switch to change between the two modes.

So each time the switch is toggled I set App.Current.UserAppTheme=OSAppTheme.Dark or App.Current.UserAppTheme=OSAppTheme.Light.

This is set correctly as the Application.Current.RequestedThemeChanged is triggered and if I check the UserAppTheme I get the correct value. And the properties I manually set with the AppThemeBinding change. But the background for example stays the same.

If I change the Theme in the phone settings and restart the app, a different background color is shown.

So is it possible to let the OS choose the colors or do I have to create and set fixed style sheets?

1

There are 1 answers

4
Jessie Zhang -MSFT On

So is it possible to let the OS choose the colors

Of course, you can set the colors you want.

The steps are as follows:

1.define the colors in file App.xaml.

For example, you can add a light color ad a dark color:

<Application.Resources>

        <!-- Light colors -->
        <Color x:Key="LightPageBackgroundColor">Yellow</Color>

        <!-- Dark colors -->
        <Color x:Key="DarkPageBackgroundColor">Red</Color>

</Application.Resources>

2.Then, in your app, you can set the BackgroundColor for ContentPage as follows:

<?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"
             xmlns:local="clr-namespace:SystemThemesDemo"
             x:Class="SystemThemesDemo.Views.UserSummaryPage"
             Title="User Summary"

             BackgroundColor="{AppThemeBinding Light={StaticResource LightPageBackgroundColor}, Dark={StaticResource DarkPageBackgroundColor}}">

</ContentPage>

Update:

You can also define a global style in App.xaml:

    <Style TargetType="NavigationPage"  x:Key="MyPageStyle">

        <Setter Property="BackgroundColor"
                Value="{AppThemeBinding Light={StaticResource LightPageBackgroundColor}, Dark={StaticResource DarkPageBackgroundColor}}" />
    </Style>

And apply it to the ContentPages you want:

<?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="SystemThemesDemo.Views.MyPage"
         Title="TestPage"
         
          Style="{StaticResource MyPageStyle}"
        >

 </ContentPage>

For more information, you can check document:Theme an app.

You can also check the official samples here: SystemThemesDemo and ThemingDemo.