How do I subscribe to PropertyChanged event in my ViewModel?

我们两清 提交于 2019-11-28 10:49:38

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!

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;
    }
}

The direct way to subscribe to property changes is using INotifyPropertyChanged if your BaseViewModel implements it:

PropertyChanged += (obj, args) =>
   { System.Console.WriteLine("Property " + args.PropertyName + " changed"); }

If it doesn't, then it has to be a DependencyObject, and your properties have to be DependencyProperties (which is probably a more complicated way).

This article describes how to subscribe for DependencyProperty changes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!