简单地说,我可以在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";
}
}
答案 0 :(得分:3)
如果属性已更改,则仅触发这些回调,您的代码不会创建不同值的无限循环。
试试这个,你会得到一个SO异常:
private static readonly Random _random = new Random();
private static void PropBChanged(DependencyObject lDependencyObject, DependencyPropertyChangedEventArgs lDependencyPropertyChangedEventArgs)
{
((MainWindow)lDependencyObject).PropA = _random.Next().ToString();
}
private static void PropAChanged(DependencyObject lDependencyObject, DependencyPropertyChangedEventArgs lDependencyPropertyChangedEventArgs)
{
((MainWindow)lDependencyObject).PropB = _random.Next().ToString();
}