尝试继承主题/样式并应用其他触发器

时间:2011-10-19 20:14:02

标签: wpf xaml styles themes derived

我正在尝试使用,并了解样式的XAML层次结构...简单,一个简单的文本框......在各地看到如何基于“IsEnabled”设置“禁用”背景颜色旗。太好了,得到了。

现在,我想要另一个派生自TextBox ... MyTextBox的类。对于这个类,我有一个属性(不是依赖属性,所以我使用的是DataTrigger)。所以,我想保留所有正常的TextBox动作,但现在获得新的触发器以正确地将背景颜色更新为其他颜色..所以,这就是我所拥有的。只是为了澄清,我所有的颜色静态资源都是坚固的刷子......

<Style TargetType="TextBox" >
  <Setter Property="FontFamily" Value="Courier New" />
  <Setter Property="FontSize" Value="12" />
  <Setter Property="Foreground" Value="{StaticResource MyForeground}" />
  <Setter Property="Background" Value="{StaticResource MyBackground}" />
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="TextBox">
        <Border Name="Bd" BorderThickness="{TemplateBinding BorderThickness}" 
            BorderBrush="{TemplateBinding BorderBrush}"
            Background="{TemplateBinding Background}" 
            SnapsToDevicePixels="true">

            <ScrollViewer Name="PART_ContentHost" 
                Background="{TemplateBinding Background}" 
                SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
        </Border>

        <ControlTemplate.Triggers>
          <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Background" Value="{StaticResource MyDisBackground}" />
            <Setter TargetName="PART_ContentHost" Property="Background" 
                 Value="MyDisBackground"/>
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

<!--  Now, my derived (or so I was hoping) style that just adds additional trigger -->
<Style TargetType="local:MyTextBox"  BasedOn="{StaticResource {x:Type TextBox}}" >
  <Style.Triggers>
    <DataTrigger Binding="{Binding Path=IsRequired}" Value="True">
      <Setter Property="Background" Value="{StaticResource RequiredBackground}" />
    </DataTrigger>
  </Style.Triggers>
</Style>

我错过了一些简单的东西吗?

1 个答案:

答案 0 :(得分:1)

首先,您的DataTrigger正在查看DataContext的{​​{1}}(不是控件本身)。所以看看控件,你需要做类似的事情:

MyTextBox

现在,当<DataTrigger Binding="{Binding Path=IsRequired, RelativeSource={RelativeSource Self}}" Value="True"> <Setter Property="Background" Value="{StaticResource RequiredBackground}" /> </DataTrigger> 为真时,将设置MyTextBox.Background属性。但依赖属性值有precedence order。所以上面会在视觉上改变使用的背景,如:

MyTextBox.IsRequired

在下列情况下,您的<local:MyTextBox /> 画笔将不会被使用。相反,你会看到RequiredBackground画笔:

MyDisBackground

在这种情况下,<local:MyTextBox IsEnabled="False" /> 更改为ScrollViewer.Background,不再绑定到MyDisBackground属性。 MyTextBox.Background仍为MyTextBox.Background,但不再在任何地方使用。

最后,在下列情况下,您的RequiredBackground画笔将不会被使用。

RequiredBackground

这里,本地值(黄色)在优先级列表中位于#3,而样式设置器位于#8。

如果您将属性设置为默认为false的依赖项属性,那么您可以执行以下操作:

<local:MyTextBox Background="Yellow" />

尽管TextBox不存在该属性,但它仍然可以获取依赖项属性的默认值并触发它。但由于它将被设置为TextBox,因此永远不会使用该触发器。