【发布时间】:2012-05-14 12:25:33
【问题描述】:
简单地说,我可以在 WPF 控件中创建 2 个依赖属性,并在每个属性更改通知中放置代码以更改另一个属性(即 PropA 更改集 PropB 和 PropB 更改集 PropA)。
我希望这会在它自己的背面消失,但 WPF 似乎可以很好地处理它。这实际上对我的目的非常方便,但我无法在任何地方找到这种行为。
那么发生了什么? WPF 依赖属性变更通知系统是否可以防止重入?
代表代码如下:
XAML:
<Window x:Class="WPFReentrancy1.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">
<Grid>
<TextBox Text="{Binding PropB, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</Window>
背后的代码:
public partial class MainWindow : Window
{
public string PropA
{
get { return (string)GetValue(PropAProperty); }
set { SetValue(PropAProperty, value); }
}
public static readonly DependencyProperty PropAProperty =
DependencyProperty.Register("PropA", typeof (string), typeof (MainWindow),new UIPropertyMetadata("0", PropAChanged));
public string PropB
{
get { return (string)GetValue(PropBProperty); }
set { SetValue(PropBProperty, value); }
}
public static readonly DependencyProperty PropBProperty =
DependencyProperty.Register("PropB", typeof (string), typeof (MainWindow), new UIPropertyMetadata("", PropBChanged));
private static void PropBChanged(DependencyObject lDependencyObject, DependencyPropertyChangedEventArgs lDependencyPropertyChangedEventArgs)
{
((MainWindow) lDependencyObject).PropA = (string) lDependencyPropertyChangedEventArgs.NewValue;
}
private static void PropAChanged(DependencyObject lDependencyObject, DependencyPropertyChangedEventArgs lDependencyPropertyChangedEventArgs)
{
((MainWindow) lDependencyObject).PropB =
double.Parse((string) lDependencyPropertyChangedEventArgs.NewValue).ToString("0.000");
}
public MainWindow()
{
InitializeComponent();
DataContext = this;
PropA = "1.123";
}
}
【问题讨论】:
-
没有具体的答案,但假设:考虑到 WPF 也沿着元素的树和相关属性进行递归流动,它只是“保存”(对于具体事件)它已经通过的节点并触发通知,因此如果再次遇到它们,请跳过它们。
标签: c# wpf dependency-properties