如何将 xaml 中的数据触发器绑定到代码定义的依赖属性?

ben*_*opp 5 c# data-binding xaml 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));
}
Run Code Online (Sandbox Code Playgroud)

然后我使用 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>
Run Code Online (Sandbox Code Playgroud)

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

Gaz*_*yer 5

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

<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>
Run Code Online (Sandbox Code Playgroud)