【发布时间】:2015-08-24 06:16:31
【问题描述】:
我有一个关于依赖属性值优先级的问题。 我的 .xaml 如下所示:
<Window x:Class="WpfTests.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local ="clr-namespace:WpfTests"
Title="MainWindow" Height="350" Width="525">
<Window.Style>
<Style>
<!--<Setter Property="Canvas.Background" Value="Gray"/>-->
<Style.Triggers>
<Trigger Property="local:MainWindow.IsMouseOver" Value="True">
<!--<Setter Property="local:LeistenPfeil.Symbolfarbe" Value="Red"/>-->
<Setter Property="local:MainWindow.Cursor" Value="Hand" />
<Setter Property="local:MainWindow.BG" Value="Blue"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Style>
<Grid Background="{Binding BG,Mode=TwoWay}">
<Button Content="ChangeBG" HorizontalAlignment="Center" VerticalAlignment="Center" Click="OnClick"/>
</Grid>
在我的 Codebehind 中,我创建了依赖属性“BG”,例如:
public partial class MainWindow : Window
{
public Brush BG
{
get { return (Brush)GetValue(BGProperty); }
set { SetValue(BGProperty, value); }
}
// Using a DependencyProperty as the backing store for BG. This enables animation, styling, binding, etc...
public static readonly DependencyProperty BGProperty =
DependencyProperty.Register("BG", typeof(Brush), typeof(MainWindow), new PropertyMetadata(Brushes.Black));
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
private void OnClick(object sender, RoutedEventArgs e)
{
BG = Brushes.Green;
}
}
因此,在启动时背景设置为黑色(DP 的默认值)。当鼠标悬停在背景上时变为蓝色。当我的代码隐藏中的 BG 属性发生变化时,触发器确实有效,但它对网格背景的影响消失了。 我已经在 MSDN 上阅读了这篇文章: https://msdn.microsoft.com/en-us/library/ms743230%28v=vs.110%29.aspx
我理解的问题是:为什么触发器在 BG 属性具有其默认值时起作用,而当它在后面的代码中发生变化时却不起作用? => 背景的最高优先级是网格的本地背景绑定,那么为什么触发器会起作用呢?
如何在后台代码中更改 BG 属性后让触发器再次工作?
【问题讨论】:
-
绑定
Background="{Binding BG,Mode=TwoWay}"没有设置BG属性的值。这里 BG 是绑定的源,而不是目标。
标签: c# .net wpf triggers dependency-properties