WinUI3 主题(APPTheme)设置

1、使用“用于WInUI的Template Studio”模板创建项目
在这里插入图片描述
2、点击设置,出现已添加
在这里插入图片描述

3、项目中会出现SettingsPage功能,如果需要单独的Settings功能可以新键一个没有添加设置的工程,对比后提取出需要Setting的文件放入空白工程

4、改为WinUI3 Gallery Dev里的Setting模式;主要要实现其中的点击功能,不然运行报错,例如实现下面的SelectionChanged="themeMode_SelectionChanged 方法。

<?xml version="1.0" encoding="utf-8"?>

<Page.Resources>
    <Style x:Key="BodyStrongTextBlockStyle" TargetType="TextBlock" BasedOn="{StaticResource BaseTextBlockStyle}">
        <Setter Property="FontSize" Value="{StaticResource BodyStrongTextBlockFontSize}" />
    </Style>
    
    <x:Double x:Key="SettingsCardSpacing">3</x:Double>

     
    <Style
        x:Key="SettingsSectionHeaderTextBlockStyle"
        BasedOn="{StaticResource BodyStrongTextBlockStyle}"
        TargetType="TextBlock">
        <Style.Setters>
            <Setter Property="Margin" Value="1,29,0,5" />
        </Style.Setters>
    </Style>
    <Style x:Key="TitleTextBlockStyle" TargetType="TextBlock" BasedOn="{StaticResource BaseTextBlockStyle}">
        <Setter Property="FontSize" Value="{StaticResource TitleTextBlockFontSize}" />
        <Setter Property="OpticalMarginAlignment" Value="TrimSideBearings" />
    </Style>
    
    <x:Double x:Key="Breakpoint640Plus">641</x:Double>
    <x:String x:Key="AppTitleName">WinUI 3 Gallery</x:String>
    
</Page.Resources>
<Grid x:Name="RootGrid">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup>
            <VisualState x:Name="WideLayout">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="{StaticResource Breakpoint640Plus}" />
                </VisualState.StateTriggers>
            </VisualState>
            <VisualState x:Name="NarrowLayout">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="0" />
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <Setter Target="contentSV.Padding" Value="16,0" />
                    <Setter Target="PageHeader.Margin" Value="16,48,0,0" />
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
    <TextBlock
        x:Name="PageHeader"
        Margin="36,24,36,0"
        Style="{StaticResource TitleTextBlockStyle}"
        Text="Settings" />
    <ScrollViewer
        x:Name="contentSV"
        Grid.Row="1"
        Padding="36,0,36,0"
        IsTabStop="False"
        UseSystemFocusVisuals="False"
        VerticalScrollBarVisibility="Auto"
        VerticalScrollMode="Auto">
        <StackPanel Spacing="{StaticResource SettingsCardSpacing}">
            <StackPanel.ChildrenTransitions>
                <EntranceThemeTransition FromVerticalOffset="50" />
                <RepositionThemeTransition IsStaggeringEnabled="False" />
            </StackPanel.ChildrenTransitions>
            <TextBlock Style="{StaticResource SettingsSectionHeaderTextBlockStyle}" Text="Appearance &amp; behavior" />
            <labs:SettingsCard Description="请选择主题" Header="主题">
                <labs:SettingsCard.HeaderIcon>
                    <FontIcon Glyph="&#xE790;" />
                </labs:SettingsCard.HeaderIcon>
                <ComboBox x:Name="themeMode" AutomationProperties.AutomationId="themeModeComboBox" SelectionChanged="themeMode_SelectionChanged">
                    <ComboBoxItem Content="Use system setting" Tag="Default" />
                    <ComboBoxItem Content="Light" Tag="Light" />
                    <ComboBoxItem Content="Dark" Tag="Dark" />
                    
                </ComboBox>
            </labs:SettingsCard>

            <labs:SettingsCard Header="Navigation style">
                <labs:SettingsCard.HeaderIcon>
                    <FontIcon Glyph="&#xF594;" />
                </labs:SettingsCard.HeaderIcon>
                <ComboBox x:Name="navigationLocation" SelectionChanged="navigationLocation_SelectionChanged">
                    <ComboBoxItem Content="Left" />
                    <ComboBoxItem Content="Top" />
                </ComboBox>
            </labs:SettingsCard>

            <labs:SettingsExpander Description="Controls provide audible feedback" Header="Sound">
                <labs:SettingsExpander.HeaderIcon>
                    <FontIcon Glyph="&#xEC4F;" />
                </labs:SettingsExpander.HeaderIcon>
                <ToggleSwitch x:Name="soundToggle" Toggled="soundToggle_Toggled" />
                <labs:SettingsExpander.Items>
                    <labs:SettingsCard
                        x:Name="SpatialAudioCard"
                        Header="Enable Spatial Audio"
                        IsEnabled="False">
                        <labs:SettingsCard.Description>
                            <HyperlinkButton Click="soundPageHyperlink_Click" Content="Learn more about enabling sounds in your app" />
                        </labs:SettingsCard.Description>
                        <ToggleSwitch x:Name="spatialSoundBox" Toggled="spatialSoundBox_Toggled" />
                    </labs:SettingsCard>
                </labs:SettingsExpander.Items>
            </labs:SettingsExpander>

            <labs:SettingsExpander x:Name="ScreenshotCard" Header="Screenshot mode">
                <labs:SettingsExpander.HeaderIcon>
                    <FontIcon Glyph="&#xEC4F;" />
                </labs:SettingsExpander.HeaderIcon>
                <ToggleSwitch x:Name="screenshotModeToggle" Toggled="screenshotModeToggle_Toggled" />
                <labs:SettingsExpander.Items>
                    <labs:SettingsCard x:Name="ScreenshotFolderCard" Header="Screenshot folder">
                        <labs:SettingsCard.Description>
                            <HyperlinkButton x:Name="screenshotFolderLink" Click="screenshotFolderLink_Click" />
                        </labs:SettingsCard.Description>
                        <Button Click="FolderButton_Click" Content="Browse" />
                    </labs:SettingsCard>
                </labs:SettingsExpander.Items>
            </labs:SettingsExpander>

            
            <TextBlock Style="{StaticResource SettingsSectionHeaderTextBlockStyle}" Text="About" />
            <labs:SettingsExpander Description="© 2023 Microsoft. All rights reserved." Header="{StaticResource AppTitleName}">
                <labs:SettingsExpander.HeaderIcon>
                    <BitmapIcon ShowAsMonochrome="False" UriSource="/Assets/Tiles/SmallTile-sdk.png" />
                </labs:SettingsExpander.HeaderIcon>
                <TextBlock
                    Foreground="{ThemeResource TextFillColorSecondaryBrush}"
                    IsTextSelectionEnabled="True"
                    Text="{x:Bind Version}" />
                <labs:SettingsExpander.Items>
                    <labs:SettingsCard Header="To clone this repository">
                        <TextBlock
                            Foreground="{ThemeResource TextFillColorSecondaryBrush}"
                            IsTextSelectionEnabled="True"
                            Text="git clone https://github.com/microsoft/WinUI-Gallery" />
                    </labs:SettingsCard>
                    <labs:SettingsCard
                        x:Name="bugRequestCard"
                        Click="bugRequestCard_Click"
                        Header="File a bug or request new sample"
                        IsClickEnabled="True">
                        <labs:SettingsCard.ActionIcon>
                            <FontIcon Glyph="&#xE8A7;" />
                        </labs:SettingsCard.ActionIcon>
                    </labs:SettingsCard>
                    <labs:SettingsCard
                        HorizontalContentAlignment="Left"
                        ContentAlignment="Vertical"
                        Header="Dependencies &amp; references">
                        <StackPanel Margin="-12,0,0,0" Orientation="Vertical">
                            <HyperlinkButton Content="111" NavigateUri="https://aka.ms/windowsappsdk" />
                            <HyperlinkButton Content="Windows UI Library" NavigateUri="https://aka.ms/winui" />
                            <HyperlinkButton Content="Windows Community Toolkit" NavigateUri="https://github.com/CommunityToolkit/WindowsCommunityToolkit" />
                            <HyperlinkButton Content="ColorCode-Universal" NavigateUri="https://github.com/WilliamABradley/ColorCode-Universal" />
                            <HyperlinkButton Content="Win2D" NavigateUri="https://github.com/Microsoft/Win2D" />
                        </StackPanel>
                    </labs:SettingsCard>
                    <labs:SettingsCard
                        HorizontalContentAlignment="Left"
                        ContentAlignment="Vertical"
                        Header="THIS CODE AND INFORMATION IS PROVIDED ‘AS IS’ WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.">
                        <StackPanel Margin="-12,0,0,0" Orientation="Vertical">
                            <HyperlinkButton Content="Microsoft Services Agreement" NavigateUri="https://go.microsoft.com/fwlink/?LinkId=822631" />
                            <HyperlinkButton Content="Microsoft Privacy Statement" NavigateUri="https://go.microsoft.com/fwlink/?LinkId=521839" />
                        </StackPanel>
                    </labs:SettingsCard>
                </labs:SettingsExpander.Items>
            </labs:SettingsExpander>
        </StackPanel>
    </ScrollViewer>
</Grid>

5、在App.xaml.cs中加入依赖
services.AddSingleton<IThemeSelectorService, ThemeSelectorService>();
services.AddSingleton<ILocalSettingsService, LocalSettingsService>();

        services.AddSingleton<IFileService, FileService>();
         services.AddTransient<AppThemeTest>();
          services.Configure<LocalSettingsOptions>(context.Configuration.GetSection(nameof(LocalSettingsOptions)));

6、实现代码
public string Version
{
get
{
var version = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Version ?? new Version(0,0,0,0) ;
return string.Format(“{0}.{1}.{2}.{3}”, version.Major, version.Minor, version.Build, version.Revision);
}
}

public AppThemeTest()
{
this.InitializeComponent();

    Loaded += AppThemeTest_Loaded;
}

private void AppThemeTest_Loaded(object sender, RoutedEventArgs e)
{
    themeMode.SelectedIndex = 0;

    _elementTheme = (ElementTheme)themeMode.SelectedIndex;
}

private async void themeMode_SelectionChanged(object sender, SelectionChangedEventArgs e)
{

    if (_elementTheme!= (ElementTheme)themeMode.SelectedIndex)
    {
        _elementTheme= (ElementTheme)themeMode.SelectedIndex;
     
        await App.GetService<IThemeSelectorService>().SetThemeAsync(_elementTheme);
    }
     

}

猜你喜欢

转载自blog.csdn.net/weixin_43780907/article/details/132300058