WPF中的datatrigger

来源:互联网 发布:ubuntu 10.04 源 编辑:程序博客网 时间:2024/04/25 11:55

<Window x:Class="triggertest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="triggertest" Height="300" Width="300"
    >
  <StackPanel Width="200">
    <StackPanel.Resources>
      <Style TargetType="{x:Type TextBox}">
      
        <Style.Triggers>
          <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text}" Value="disabled">
            <Setter Property="IsEnabled" Value="False"/>
          </DataTrigger>
        </Style.Triggers>
       
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Path=Text}"/>
        <!--Setter Property="IsEnabled"  Value="{Binding RelativeSource={RelativeSource Self}, Path=Text}"/-->
      </Style>
    </StackPanel.Resources>
    <TextBox Margin="30"/>
  </StackPanel>
</Window> 

当输入disabled的时候,窗口被禁止

蓝色注释掉的有同样的效果,只不过要输入False

关于RelativeSource

 

Binding’s RelativeSource
Another way to specify a data source is with Binding’s RelativeSource property, which
refers to an element by its relationship to the target element. The property is of type
RelativeSource, which also happens to be a markup extension. Here are some of the ways
RelativeSource can be used:
To make the source element equal the target element:
{Binding RelativeSource={RelativeSource Self}}
To make the source element equal the target element’s TemplatedParent (a property
discussed in the next chapter):
{Binding RelativeSource={RelativeSource TemplatedParent}}
To make the source element equal the closest parent of a given type:
{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type
desiredType}}}
To make the source element equal the nth closest parent of a given type:
{Binding RelativeSource={RelativeSource FindAncestor,
AncestorLevel=n, AncestorType={x:Type desiredType}}}
To make the source element equal the previous data item in a data-bound collection:
{Binding RelativeSource={RelativeSource PreviousData}}
RelativeSource is especially useful for control templates, discussed in the next chapter.
But using RelativeSource with a mode of Self is handy for binding one property of an
element to another without having to give the element a name. An interesting example is the
following Slider whose ToolTip is bound to its own value:
<Slider ToolTip=”{Binding RelativeSource={RelativeSource Self}, Path=Value}”/>