通過主題設定,可以在執行時更改應用的主題外觀,比如切換亮色主題和暗黑主題。主題設定並沒有新的知識點,基本的原理如下:
一、在Themes資料夾下,建立MAUI的資源字典檔案LightTheme.xaml和DarkTheme.xaml
二、在根頁面App.xaml的資源字典中,參照預設的ResourceDictionary
<Application ......> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Resources/Styles/Colors.xaml" /> <ResourceDictionary Source="Resources/Styles/Styles.xaml" /> <!--參照預設主題資源字典LightTheme.xaml--> <ResourceDictionary Source="Themes/LightTheme.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application>
三、在App.xaml中,定義應用級別的Style(非必要)
<Application ......> <Application.Resources> <ResourceDictionary> ...... </ResourceDictionary> <!--定義Style,TargetType為Label--> <Style x:Key="PrimaryLabelStyle" TargetType="Label"> <Setter Property="TextColor" Value="{DynamicResource PrimaryTextColor}" /> <Setter Property="FontSize" Value="25" /> </Style> <Style x:Key="SecondLabelStyle" TargetType="Label"> <Setter Property="TextColor" Value="{DynamicResource SecondaryTextColor}" /> <Setter Property="FontSize" Value="30" /> </Style> </Application.Resources> </Application>
四、在頁面中通過DynamicResource擴充套件標記參照ResourceDictionary的Key值,或通過StaticResource和Style間接參照
<ContentPage ...... BackgroundColor="{DynamicResource PageBackgroundColor}"> <StackLayout BackgroundColor="{DynamicResource PrimaryColor}"> <Label Text="直接繫結ResourceDictionary的Key值①" TextColor="{DynamicResource PrimaryTextColor}"/> <Label Text="直接繫結ResourceDictionary的Key值②" TextColor="{DynamicResource SecondaryTextColor}"/> <Label Text="通過Style間接繫結ResourceDictionary①" Style="{StaticResource PrimaryLabelStyle}"/> <Label Text="通過Style間接繫結ResourceDictionary②" Style="{StaticResource PrimaryLabelStyle}"/> <Button Text="切換主題" Clicked="Button_Clicked"/> </StackLayout> </ContentPage>
五、通過後臺程式碼切換主題,本案例使用Button的點選事件
public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } private void Button_Clicked(object sender, EventArgs e) { //獲取當前資源字典 ICollection<ResourceDictionary> mergedDictionaries = Application.Current.Resources.MergedDictionaries; //先將當前資源字典清空,再添回暗黑主題DarkTheme if (mergedDictionaries != null) { mergedDictionaries.Clear(); mergedDictionaries.Add(new DarkTheme()); } } }