MVVM: Modified model, how to correctly update ViewModel and View?

后端 未结 2 658
刺人心
刺人心 2020-12-13 02:26

Case

Say I have a Person class, a PersonViewModel and a PersonView.

Updating properties from PersonView

2条回答
  •  独厮守ぢ
    2020-12-13 03:06

    If the view is binding to the Model directly then as long as the service is using the same instance any changes to the model properties will be propogated to the view.

    However if you are recreating a new model in the service then you will give the viewmodel the new model. I expect to see the model as a property on the view model so when you set that property all binding should be alerted to the change.

    //in the ViewModel
    public Person Model
    {
       get { return _person; }
       set { _person = value; 
             RaisePropertyChanged("Model");  //<- this should tell the view to update
            }
    }
    

    EDIT:

    Since you state there are specific ViewModel logic then you can tailor those properties in the ViewModel

     private void Model_PropertyChanged(object sender, PropertyChangedEventArgs e)
     {
          if(e.PropertyName == "Prop1") RaisePropertyChanged("SpecicalProperty");
          ...
     }
    
      public string SpecicalProperty
      {
         get
         {
             reutrn Model.Prop1 + " some additional logic for the view"; 
         }
       }
    

    IN XAML

        
      
    

    This way only both the Model and ViewModel propertys are bound to the view without duplicating the data.

    You can get fancier creating a helper to link the property changes from the model to the view model or use a mapping dictionary

     _mapping.Add("Prop1", new string[] { "SpecicalProperty", "SpecicalProperty2" });
    

    and then find the properties to update by getting the list of properties

     private void Model_PropertyChanged(object sender, PropertyChangedEventArgs e)
     {
    
          string[] props;
          if(_mapping.TryGetValue(e.PropertyName, out props))
          {
              foreach(var prop in props)
                  RaisePropertyChanged(prop);
          } 
     }
    

提交回复
热议问题