Good way to refresh databinding on all properties of a ViewModel when Model changes Good way to refresh databinding on all properties of a ViewModel when Model changes wpf wpf

Good way to refresh databinding on all properties of a ViewModel when Model changes


According to the docs:

The PropertyChanged event can indicate all properties on the object have changed by using either null or String.Empty as the property name in the PropertyChangedEventArgs.


One option is to listen to your own events, and make a helper routine to raise the other notifications as required.

This can be as simple as adding, in your constructor:

public FooViewModel(){    this.PropertyChanged += (o,e) =>      {          if (e.PropertyName == "Model")          {               OnPropertyChanged("FooViewModelProperty");               // Add other properties "dependent" on Model here...          }      };}


Whenever your Model property is set, subscribe to its own PropertyChanged event. When your handler gets called, fire off your own PropertyChanged event. When the Model is set to something else, remove your handler from the old Model.

Example:

class FooViewModel{    private FooModel _model;    public FooModel Model     {         get { return _model; }        set         {             if (_model != null)            {                _model.PropertyChanged -= ModelPropertyChanged;            }            if (value != null)            {                value.PropertyChanged += ModelPropertyChanged;            }            _model = value;             OnPropertyChanged("Model");         }    }    public int FooViewModelProperty    {        get { return Model.FooModelProperty; }        set         {            Model.FooModelProperty = value;            OnPropertyChanged("FooViewModelProperty");        }     }    private void ModelPropertyChanged(object sender, PropertyChangedEventArgs e)    {        // Here you will need to translate the property names from those        // present on your Model to those present on your ViewModel.        // For example:        OnPropertyChanged(e.PropertyName.Replace("FooModel", "FooViewModel"));    }}