UWP:重新定义按钮样式

UWP: Redefining Button Styles

我想通过定义明暗样式来修改我的按钮的颜色modes.I有一个样式定义如下:

<Style x:Key="ExampleButton" TargetType="Button">
    <Setter Property="FontSize" Value="14" />
    <Setter Property="FontWeight" Value="Normal" />
</Style>

在另一个文件中,我将 ButtonBackground 定义为浅色模式下的“红色”。我的期望是,当我的应用程序使用此 ExampleButton 时,它应该具有红色背景。但是,我仍然可以看到此按钮使用其默认的 BorderBackground,即 SystemControlBackgroundBaseLowBrush。我可以通过 3 种方式解决这个问题:

  1. 将 SystemControlBackgroundBaseLowBrush 重新定义为“红色”,这可行,但我可能会将 SystemControlBackgroundBaseLowBrush 用于其他控件,因此不想使用这种方法。

  2. 在上面的代码中再添加一个setter就可以得到类似这样的东西

     <Style x:Key="ExampleButton" TargetType="Button">
       <Setter Property="FontSize" Value="14" />
       <Setter Property="FontWeight" Value="Normal" />
       <Setter Property="Background" Value="Red"/>
    </Style>
    
  3. 编辑按钮模板中的值

哪个是实现此目标的最优雅的解决方案?除了我上面描述的 3 个之外,还有更好的解决方案吗?

我希望避免添加整个模板来修改颜色

#2 将是最佳解决方案,但需要在 ResourceDictionary.ThemeDictionaries

中某处定义 {ThemeResource MyBrush} 和 MyBrush 而不是只有 Red

确实最好的方法是定义一个 SolidColorBrush,它根据应用程序主题而有所不同。首先,您应该像这样向 Application.ResourcesPage.Resources 添加一个 ResourceDictionary.ThemeDictionaries。然后将此 SolidColorBrush 设置为按钮样式的 BackGround 属性 的值,如下所示:

<Page
    ....
    RequestedTheme="Light">
    <!--Red button, or set to "Dark" for a blue button, remove this line or set to "Auto" to choose device theme-->
    
    <Page.Resources>
        <ResourceDictionary>
            <ResourceDictionary.ThemeDictionaries>
                <ResourceDictionary x:Key="Light">
                    <SolidColorBrush x:Key="CustomButtonBackGroundColor" Color="Red"/>
                </ResourceDictionary>
                <ResourceDictionary x:Key="Dark">
                    <SolidColorBrush x:Key="CustomButtonBackGroundColor" Color="Blue"/>
                </ResourceDictionary>
            </ResourceDictionary.ThemeDictionaries>

            <Style x:Key="ExampleButtonStyle" TargetType="Button">
                <Setter Property="FontSize" Value="14"/>
                <Setter Property="FontWeight" Value="Normal"/>
                <Setter Property="Background" Value="{ThemeResource CustomButtonBackGroundColor}"/>
            </Style>
        </ResourceDictionary>
    </Page.Resources>
</Page>

然后你可以像这样添加你的按钮:

<Button Content="Example Button" Style="{StaticResource ExampleButtonStyle}"/>