C # / WPF: PropertyChanged for all properties in ViewModel?

I have a class like this:

public class PersonViewModel : ViewModelBase //Here is the INotifyPropertyChanged Stuff { public PersonViewModel(Person person) { PersonEntity = person; } public Person PersonEntity { get { return PersonEntity.Name; } private set { PersonEntity.Name = value; RaisePropertyChanged("PersonEntity"); } public string Name { get { return PersonEntity.Name; } set { PersonEntity.Name = value; RaisePropertyChanged("Name"); } public int Age{ get { return PersonEntity.Age; } set { PersonEntity.Age= value; RaisePropertyChanged("Age"); } public void ChangePerson(Person newPerson) { //Some Validation.. PersonEntity = newPerson; } 

My text fields are bound to the name and age of the ViewModel. If I change the _person object in the ViewModel, do I need to call RaisePropertyChanged again for each property, or is there a way to do this automatically (in my specific example, I have about 15 properties.)?

Thanks for any help.

Cheers Joseph

+53
c # wpf inotifypropertychanged
Dec 07 '09 at 13:21
source share
2 answers

You can indicate that all properties have been changed using null or string.Empty for the property name in PropertyChangedEventArgs . This is mentioned in the documentation for PropertyChanged .

+99
Dec 07 '09 at 13:48
source share
— -

Another solution I used to solve the problem: first set the value and then call PropertyChangedEventArgs , adding the Set function to my ViewModelBase , which looks like this:

 public class ViewModelBase : INotifyPropertyChanged { protected bool Set<T>(ref T backingField, T value, [CallerMemberName] string propertyname = null) { // Check if the value and backing field are actualy different if (EqualityComparer<T>.Default.Equals(backingField, value)) { return false; } // Setting the backing field and the RaisePropertyChanged backingField = value; RaisePropertyChanged(propertyname); return true; } } 

Instead of this:

 public string Name { get { return PersonEntity.Name; } set { PersonEntity.Name = value; RaisePropertyChanged("Name"); } 

Now you can achieve the same by doing this:

 public string Name { get { return PersonEntity.Name; } set { Set(ref PersonEntity.Name,value); } 
0
Jul 25 '19 at 20:23
source share



All Articles