改变一下步骤,先借鉴别人的文章描述一下主题。
通过主题设置,可以在运行时更改应用的主题外观,比如切换亮色主题和暗黑主题。主题设置并没有新的知识点,基本的原理如下:
- 定义每个应用主题的ResourceDictionary,每个ResourceDictionary有相同的Key,但值不同。
- 在根页面App.xaml的资源字典中,引用默认的ResourceDictionary。
- 使用方式①:直接在页面中,通过DynamicResource扩展标记,引用ResourceDictionary的Key值。
- 使用方式②:在App.xaml中,定义应用级别的Style,样式值使用DynamicResource扩展标记,引用ResourceDictionary的Key值。页面中,则使用StaticResource扩展标记引用Style。
- 如需在运行时更改主题,通过后台代码更换ResourceDictionary即可。
创建主题文件
在Themes文件夹下添加主题文件。
根据需要设置
引用主题
全局引用
根页面App.xaml的资源字典中,引用默认的ResourceDictionary
<ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="StudyMaui.Themes.LightTheme">
<Color x:Key="PageBackgroupColor">White</Color>
<Color x:Key="PrimaryColor">Blue</Color>
<Color x:Key="SecondaryTextColor">Green</Color>
</ResourceDictionary>
在页面中通过DynamicResource扩展标记引用ResourceDictionary的Key值,或通过StaticResource和Style间接引用
x:Class="StudyMaui.MainPage"
BackgroundColor="{DynamicResource PageBackgroundColor}">
<StackLayout BackgroundColor="{DynamicResource PrimaryColor}">
<Label Text="直接绑定ResourceDictionary的Key值②" TextColor="{DynamicResource SecondaryTextColor}"/>
<Button Text="切换主题" Clicked="Button_Clicked"/>
<Label
FontAttributes="Bold,Italic"
FontAutoScalingEnabled="True"
FontFamily="Nabla_Regular"
FontSize="30"
Text="字体基本使用" />
<ImageButton>
<ImageButton.Source>
<FontImageSource
FontFamily="Nabla_Regular"
Glyph=""
Size="20"
Color="DarkBlue" />
</ImageButton.Source>
</ImageButton>
</StackLayout>
代码切换
private void Button_Clicked(object sender, EventArgs e)
{
//获取当前资源字典
ICollection<ResourceDictionary> mergedDictionaries = Application.Current.Resources.MergedDictionaries;
//先将当前资源字典清空,再添回主题
if (mergedDictionaries != null)
{
mergedDictionaries.Clear();
mergedDictionaries.Add(new LightTheme());
}
}
}
效果图: