如何将xaml中的数据触发器绑定到代码定义的依赖项属性
本文关键字:代码 定义 依赖 属性 绑定 触发器 xaml 数据 | 更新日期: 2023-09-27 18:10:09
我的窗口代码定义了一个依赖属性"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>
选中一个方框会自动选中另一个方框,但不会改变矩形的颜色:(
本地设置的属性总是覆盖样式设置属性,所以你需要删除本地设置的属性,并在你的样式中设置默认值:
<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>
一旦设置了属性,样式在该属性上定义的触发器将不再工作。你可以定义另一个datattrigger来改变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>