Maui提供了一种根据当前应用程序主题设置属性的机制,但是它不包含用于在UI中切换主题的组件,需要我们自行创建。
创建项目
-
首先创建一个ThemeInfo类来存储应用程序主题对象及标题。这些对象会在Picker元素中显示。
-
添加CommunityToolkit.Mvvm工具包,创建一个ThemeSettings主题设置类,来存储可用主题列表和当前可选主题。
public partial class ThemeInfo
{
public static ThemeInfo System = new(AppTheme.Unspecified, "System");
public static ThemeInfo Light = new(AppTheme.Light, "Light");
public static ThemeInfo Dark = new(AppTheme.Dark, "Dark");
public AppTheme Theme { get; }
public string Caption { get; }
public ThemeInfo(AppTheme theme, string caption)
{
Theme = theme;
Caption = caption;
}
}
public partial class ThemeSettings:ObservableObject
{
public static List<ThemeInfo> ThemeList { get; } =
[
ThemeInfo.System,
ThemeInfo.Light,
ThemeInfo.Dark
];
public static ThemeSettings Current { get; } = new ThemeSettings();
[ObservableProperty] private ThemeInfo selectedTheme = ThemeList.First();
partial void OnSelectedThemeChanged(ThemeInfo oldValue,ThemeInfo newValue)
{
App.Current.UserAppTheme = newValue.Theme;
}
}
-
主页中使用Picker元素更改主题。
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MauiApp2;"
x:DataType="{x:Type local:ThemeInfo}"
x:Class="MauiApp2.MainPage">
<Grid>
<Picker
ItemsSource="{Binding Source={x:Static local:ThemeSettings.ThemeList}}"
SelectedItem="{Binding Source={x:Static local:ThemeSettings.Current},Path=SelectedTheme}"
ItemDisplayBinding="{Binding Caption}"
VerticalOptions="Center"
HorizontalOptions="Center"/>
</Grid>
</ContentPage>
IOS下运行程序
根据当前主题更改图像和状态栏
-
在Resources/Image下添加一个SVG文件,属性中设置为MauiImage。
-
在主页引入图片源,注意虽然添加的是SVG文件,但在使用时后缀为png,因为Maui在构建项目时会将SVG转换为png。
-
使用CommunityToolkit.Maui工具包中的 IconTintColorBehavior来更改图片颜色。StatusBarBehavior来修改状态栏颜色。
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MauiApp2;"
x:DataType="{x:Type local:ThemeInfo}"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
x:Class="MauiApp2.MainPage">
<ContentPage.Behaviors>
<toolkit:StatusBarBehavior
StatusBarColor="{Binding Source={x:Reference label1},Path=TextColor}"/>
</ContentPage.Behaviors>
<VerticalStackLayout>
<Image Source="mark.png">
<Image.Behaviors>
<toolkit:IconTintColorBehavior
TintColor="{Binding Source={x:Reference label1},Path=TextColor}"/>
</Image.Behaviors>
</Image>
<Label
x:Name="label1"
Text="Hello"
TextColor="{AppThemeBinding Dark=Orange,Light=Gray}"/>
<Picker
ItemsSource="{Binding Source={x:Static local:ThemeSettings.ThemeList}}"
SelectedItem="{Binding Source={x:Static local:ThemeSettings.Current},Path=SelectedTheme}"
ItemDisplayBinding="{Binding Caption}"
VerticalOptions="Center"
HorizontalOptions="Center"/>
</VerticalStackLayout>
</ContentPage>
IOS下运行程序
标签:笔记,get,主题,ThemeInfo,AppTheme,切换,Maui,static,public From: https://blog.csdn.net/hivv510/article/details/145260215