How WPF framework handles cyclic update of propert

2019-02-26 21:24发布

问题:

Lets assume property Name is bind to TextBox in view like this.

private string name
public string Name
{
   get {return name;}
   set {
       name=value;
       OnPropertyChanged("Name");
   }
}

View

<TextBox Text="{Binding Name, Mode=TwoWay"/>

When we update the text in text box, it will call the setter in Name property which in turn raise PropertyChanged which suppose to update UI again. I am curious how WPF avoid recursion of update and raise event. is it done by considering the sender of that event?

回答1:

A standard implementation of a property should look like this:

private string name;

public string Name
{
   get { return name; }

   set
   {
       if( name != value )
       {
           name = value;
           OnPropertyChanged("Name");
       }
   }
}

Note the additional if to make sure the event is only raised if the value of the property actually changed.



回答2:

There is no recursion as far I understand.

1) TextBox updates the value using viewmodel property.

2) Viewmodel raises update, letting UI know that something changed

3) TextBox now updates himself to match the viewmodel value.



回答3:

may the answer from here help you out.

if you set a property from ui to viewmodel it goes like this.

  • setter call started
  • value set
  • INotifyPropertyChanged started
  • INotifyPropertyChanged done
  • setter done
  • getter called and done
  • IDataErrorInfo called and done

but if you set the property in your viewmodel it goes like this

  • setter call started
  • value set
  • INotifyPropertyChanged started
  • getter called and done
  • IDataErrorInfo called and done
  • INotifyPropertyChanged done
  • setter done

Changing property from UI to ViewModel may lead to deadlock kind of situation which might run into end less recursive calls in two way scenarios. In order to block this from happening, when WPF is making change to model, it will continue to track changes via INotifyPropertyChanged ,but this change will be queued in dispatcher queue, and it will be executed after its current update is finished.

Since the change in viewmodel is not initiated by WPF, WPF will not queue the operation, it will immediately execute the change.



标签: c# .net wpf xaml mvvm