如何将xaml中的datatrigger绑定到代码定义的依赖项属性?

时间:2013-04-19 23:31:49

标签: c# xaml data-binding datatrigger

我在窗口后面的代码定义了一个依赖属性,“Active”......

public partial class MainWindow : Window
{
  public MainWindow() { InitializeComponent(); }

  public bool Active
  {
     get { return (bool) GetValue(ActiveProperty); }
     set { SetValue(ActiveProperty, value); }
  }
  public static readonly DependencyProperty ActiveProperty =
      DependencyProperty.Register("Active", typeof(bool), typeof(MainWindow), new UIPropertyMetadata(false));
}

然后我使用xaml中的两个复选框绑定到该属性。我还想根据该属性更改矩形的填充。我怎样才能做到这一点?

<Window x:Class="WpfTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="350"
        Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
  <StackPanel>
    <CheckBox IsChecked="{Binding Active}" />
    <CheckBox IsChecked="{Binding Active}" />
    <Rectangle Fill="Gray"
               Width="50"
               Height="50">
      <Rectangle.Style>
        <Style TargetType="Rectangle">
          <Style.Triggers>
            <DataTrigger Binding="{Binding Active}"
                         Value="True">
              <Setter Property="Fill"
                      Value="Green" />
            </DataTrigger>
          </Style.Triggers>
        </Style>
      </Rectangle.Style>
    </Rectangle>
  </StackPanel>
</Window>

选中一个框会自动检查另一个,但不会更改矩形颜色:(

2 个答案:

答案 0 :(得分:3)

本地设置属性始终覆盖样式集属性,因此您需要删除本地设置属性并在样式中设置默认值:

<Rectangle Width="50" Height="50">
    <Rectangle.Style>
        <Style TargetType="Rectangle">
            <Setter Property="Fill" Value="Gray" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Active}" Value="True">
                    <Setter Property="Fill" Value="Green"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Rectangle.Style>
</Rectangle>

答案 1 :(得分:2)

设置属性后,样式在此属性上定义的触发器将不再起作用。您可以定义另一个dataTrigger来更改False值的背景:

  <StackPanel>
        <CheckBox IsChecked="{Binding Active}"/>
        <CheckBox IsChecked="{Binding Active}"/>
        <Rectangle Width="50" Height="50">
            <Rectangle.Style>
                <Style TargetType="Rectangle">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Active}" Value="True">
                            <Setter Property="Fill" Value="Green"/>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding Active}" Value="false">
                            <Setter Property="Fill" Value="Gray"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Rectangle.Style>
        </Rectangle>
    </StackPanel>