首页 > 解决方案 > 悬停圆角按钮使用 ResourceDictionary 更改其背景颜色

问题描述

我创建了一个名为 btn_default 的样式的 ResourceDictionary 样式表。我打算在我的程序中的所有按钮上使用它。我的问题是,当我悬停按钮时,背景颜色不会改变。字体颜色发生变化。

button_default

在此处输入图像描述

button_default:悬停

在此处输入图像描述

我尝试在我的代码中更改“Setter Property="Background" Value="#b5b5b5"”,但是我猜这不会影响 Border-tag,但 Style-tag?

资源字典

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MSDNSample">

    <!-- Btn default -->
    <Style x:Key="btn_default" TargetType="{x:Type Button}">
        <Setter Property="FontFamily" Value="Calibri"/>
        <Setter Property="FontSize" Value="14"/>
        <Setter Property="Foreground" Value="#d9d9d9" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border CornerRadius="5" BorderThickness="1" Padding="6,4,6,4" Background="#6c6c6c" BorderBrush="#393939">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="#b5b5b5"/>
                            <Setter Property="Foreground" Value="#000000" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>

            </Setter.Value>
        </Setter>
    </Style>
    <!-- //Btn default -->
</ResourceDictionary>

主要的

<Button x:Name="buttonExplorer" Content="Explorer" Style="{StaticResource btn_default}" Margin="0,0,6,0" />
<Button x:Name="buttonProcess" Content="Process" Style="{StaticResource btn_default}" Margin="0,0,6,0" />

标签: c#wpfxaml

解决方案


你应该在setter中声明使用扩展Background的属性和设置值,否则它永远不会被更新BorderTemplateBindingBackgroundStyle

<Style x:Key="btn_default" TargetType="{x:Type Button}">
   <Setter Property="FontFamily" Value="Calibri"/>
   <Setter Property="FontSize" Value="14"/>
   <Setter Property="Foreground" Value="#d9d9d9" />
   <Setter Property="Background" Value="#6c6c6c"/>
   <Setter Property="Template">
      <Setter.Value>
           <ControlTemplate TargetType="Button">
               <Border CornerRadius="5" BorderThickness="1" Padding="6,4,6,4" BorderBrush="#393939" Background="{TemplateBinding Background}">
                     <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
               </Border>
               <ControlTemplate.Triggers>
                   <Trigger Property="IsMouseOver" Value="True">
                       <Setter Property="Background" Value="#b5b5b5"/>
                       <Setter Property="Foreground" Value="#000000" />
                   </Trigger>
               </ControlTemplate.Triggers>
           </ControlTemplate>
       </Setter.Value>
   </Setter>
</Style>

推荐阅读