如何将xaml中的datatrigger绑定到代码定义的依赖项属性? [英] How do I bind a datatrigger in xaml to a code-defined dependency property?

查看:134
本文介绍了如何将xaml中的datatrigger绑定到代码定义的依赖项属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My code behind for a window defines a dependency property, "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中的两个复选框将其绑定到该属性。我也想基于该属性更改矩形的填充。我该如何进行这项工作?

And then I bind to that property using two checkboxes in xaml. I also want to change the fill of a rectangle based on that property. How can I make this work?

<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>

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

Checking one box auto-checks the other, but does not change the rectangle color :(

推荐答案

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

Locally set properties always override style set properties, so you need to remove the locally set one and set the default value in your style instead:

<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>

这篇关于如何将xaml中的datatrigger绑定到代码定义的依赖项属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆