Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I subscribe to PropertyChanged event in my ViewModel?

Tags:

I have core functionality encapsulated in ViewModelBase

Now I want to see when PropertyChanged event was raised by ViewModelBase and act on it. For example, when one property was changed on ViewModelBase - I want to change property on my ViewModel

How do I achieve this?

public class MaintainGroupViewModel : BaseViewModel<MEMGroup>     {   public abstract class BaseViewModel<T> : NotificationObject, INavigationAware         where T : Entity     { 
like image 639
katit Avatar asked Oct 19 '11 16:10

katit


People also ask

Which class subscribes to changes in ViewModel?

The ViewModel class allows data to survive configuration changes such as screen rotations.

How to use INotify Property changed?

To implement INotifyPropertyChanged you need to declare the PropertyChanged event and create the OnPropertyChanged method. Then for each property you want change notifications for, you call OnPropertyChanged whenever the property is updated.

What is the use of INotifyPropertyChanged in c#?

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed.


2 Answers

Usually I use register to the PropertyChanged event in the class Constructor

public MyViewModel() {     this.PropertyChanged += MyViewModel_PropertyChanged; } 

and my PropertyChanged event handler looks like this:

void MyViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) {     switch (e.PropertyName)     {         case "SomeProperty":             // Do something             break;     } } 
like image 85
Rachel Avatar answered Oct 16 '22 00:10

Rachel


I am concerned that you're effectively doing a 'manual binding' (bad) for a property in a derived class to a value on the base class (also bad). The whole point of using inheritance is that the derived class can access things in the base class. Use a protected modifier to indicate things should only be accessible to derived classes.

I would suggest this (potentially) more correct method:

Base class:

protected virtual void OnMyValueChanged() { } 

Derived class:

protected override void OnMyValueChanged() { /* respond here */ } 

Really, subscribing to an event in the base class of the very class you're writing just seems incredibly backwards - what's the point of using inheritance over composition if you're going to compose yourself around yourself? You're literally asking an object to tell itself when something happens. A method call is what you should use for that.

In terms of "when one property was changed on ViewModelBase - I want to change property on my ViewModel", ... they are the same object!

like image 38
Kieren Johnstone Avatar answered Oct 15 '22 23:10

Kieren Johnstone