How WPF framework handles cyclic update of properties in MVVM?

后端 未结 3 1511
無奈伤痛
無奈伤痛 2021-01-22 16:10

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

private string name
public string Name
{
   get {return name;}
   set {
       name=value;
              


        
相关标签:
3条回答
  • 2021-01-22 16:18

    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.

    0 讨论(0)
  • 2021-01-22 16:25

    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.

    0 讨论(0)
  • 2021-01-22 16:29

    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.

    0 讨论(0)
提交回复
热议问题