Property override dependency (or: why does this work?)

Simply put, I can create 2 dependency properties in a WPF control and put the code in each property change notification to change another property (i.e. PropA change PropB sets and PropB change PropA sets).

I would expect this to disappear from its back side, but WPF seems to do a great job of this. It is really very convenient for my purposes, but I can not find this behavior anywhere in the documents.

So what is going on? Does the WPF dependency notification system protect against relocation?

The following is representative code:

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> 

Code behind:

  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"; } } 
+6
source share
1 answer

These callbacks are only triggered when a property changes; your code does not create an infinite loop of different values.

Try this and you will get a SO exception:

 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(); } 
+3
source

Source: https://habr.com/ru/post/915670/


All Articles