gpt4 book ai didi

c# - 依赖属性重入(或 : why does this work? )

转载 作者:太空狗 更新时间:2023-10-29 21:51:24 24 4
gpt4 key购买 nike

简单地说,我可以在 WPF 控件中创建 2 个依赖属性,并将代码放入每个属性更改通知中以更改其他属性(即 PropA 更改集 PropBPropB 更改集 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";
}
}

最佳答案

这些回调仅在属性更改时触发,您的代码不会创建不同值的无限循环。

试试这个,你会得到一个 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();
}

关于c# - 依赖属性重入(或 : why does this work? ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10583307/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com