如果 mouseOver 已被覆盖,则无法再更改背景按钮 属性

Can't change background button property anymore if mouseOver have been overridden

在下图中,我更改了默认 mouseOver 效果的 3 个按钮 (UserControls)。在图片中,我目前将鼠标悬停在按钮 1 上。

这是我使用的代码:

<Style x:Key="ButtonMouseOver" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border>
                    <Border.Style>
                        <Style TargetType="{x:Type Border}">
                             <Style.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="Background" Value="#404040"/>
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </Border.Style>
                    <Grid Background="Transparent">
                        <ContentPresenter></ContentPresenter>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

我的用户控制按钮:

<Button HorizontalContentAlignment="Stretch" Style="{StaticResource ButtonMouseOver}" VerticalContentAlignment="Stretch" Background="{Binding ButtonColor}" BorderThickness="0">

但是现在,我无法再使用 Background 属性 更改按钮的颜色。有什么想法吗?

当您覆盖 ControlTemplate 时,您必须小心使用 TemplateBinding 绑定到模板化目标控件的属性,否则它们会采用默认值或您指定的显式值在模板中,但不能直接或在 Style.

中覆盖它们

在您的示例中,您必须将 BorderBackgroundTemplateBinding 绑定,以便它使用 Background 属性 中的值] 的模板 Button。您应该为 Button 的所有属性执行此操作以启用不同的样式。

<ControlTemplate TargetType="{x:Type Button}">
   <Border Background="{TemplateBinding Background}">
   <!-- ...other definitions -->
</ControlTemplate>

来自TemplateBindingdocumentation

Links the value of a property in a control template to be the value of another property on the templated control.

这是您的控件模板的简化版本,带有背景模板绑定,以及在其样式中定义的默认值,可以用另一种样式或直接在按钮上覆盖。

<Style x:Key="ButtonMouseOver" TargetType="{x:Type Button}">
   <Setter Property="Background"
           Value="#777777"/>
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="{x:Type Button}">
            <Border x:Name="MyBorder"
                    Background="{TemplateBinding Background}">
               <ContentPresenter HorizontalAlignment="Center"
                                 VerticalAlignment="Center"/>
            </Border>
            <ControlTemplate.Triggers>
               <Trigger Property="IsMouseOver"
                        Value="True">
                  <Setter TargetName="MyBorder"
                          Property="Background"
                          Value="#404040"/>
               </Trigger>
            </ControlTemplate.Triggers>
         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>