如果目标属性已具有显式值,则属性触发器中的setter将失败

Mal*_*oss 1 wpf xaml controltemplate

我目前正在尝试为WPF中ControlTemplateButton类创建一个类,用通常的可视化树取代使得按钮看起来类似于Google Chrome选项卡上的小(X)关闭图标.我决定Path在XAML中使用一个对象来实现这个效果.使用属性触发器,控件通过设置图标的红色背景来响应IsMouseOver属性的更改.

这是来自测试应用程序的XAML:

<Window x:Class="Widgets.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">

  <Window.Resources>
    <Style x:Key="borderStyle" TargetType="Border">
      <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
          <Setter Property="Background">
            <Setter.Value>
              <SolidColorBrush Color="#CC0000"/>
            </Setter.Value>
          </Setter>
        </Trigger>
      </Style.Triggers>
    </Style>

    <ControlTemplate x:Key="closeButtonTemplate" TargetType="Button">
      <Border Width="12" Height="12" CornerRadius="6"
              BorderBrush="#AAAAAA" Background="Transparent"
              Style="{StaticResource borderStyle}"
              ToolTip="Close">
        <Viewbox Margin="2.75">
          <Path Data="M 0,0 L 10,10 M 0,10 L 10,0" Stroke="{Binding BorderBrush, RelativeSource={RelativeSource FindAncestor, AncestorType=Border, AncestorLevel=1}}" StrokeThickness="1.8"/>
        </Viewbox>
      </Border>
    </ControlTemplate>
  </Window.Resources>

  <Grid Background="White">
    <Button Template="{StaticResource closeButtonTemplate}"/>
  </Grid>

</Window>
Run Code Online (Sandbox Code Playgroud)

请注意,圆形背景始终存在 - 当鼠标悬停在圆形背景上时,它只是透明的.

这个问题是触发器无法正常工作.按钮的外观没有任何变化.但是,如果我Background="Transparent"从中移除Border对象中的值ControlTemplate,则触发器可以正常工作(尽管只有当超过'X'时).

我实在无法解释这一点.放置在borderStyle资源中的任何其他属性的setter都可以正常工作,但是Background一旦在ControlTemplate.中指定了默认背景,setter就会失败.

任何想法为什么会发生以及如何解决它?我知道我可以轻松地用例如基于.PNG的图像替换此代码,但我想了解当前实现无效的原因.

谢谢!:)

Mat*_*ton 6

尝试将边框声明中的明确"背景"赋值移动到样式本身:

<Style x:Key="borderStyle" TargetType="Border">
    <Setter Property="Background" Value="Transparent" />

    <Style.Triggers> 
        <Trigger Property="IsMouseOver" Value="True"> 
            <Setter Property="Background"> 
            <Setter.Value> 
                <SolidColorBrush Color="#CC0000"/> 
            </Setter.Value> 
        </Setter> 
    </Trigger> 
</Style.Triggers> 

...

<Border Width="12" Height="12" CornerRadius="6" 
        BorderBrush="#AAAAAA" 
        Style="{StaticResource borderStyle}" 
        ToolTip="Close"> 
Run Code Online (Sandbox Code Playgroud)

样式不能覆盖已显式设置的属性.您需要在样式中设置值.