如何在 ViewModel 中订阅 PropertyChanged 事件?
我将核心功能封装在 ViewModelBase 中
现在我想查看 ViewModelBase 何时引发 PropertyChanged 事件并对其采取行动。例如,当 ViewModelBase 上的一个属性发生更改时 - 我想更改 ViewModel 上的属性,
如何实现这一目标?
public class MaintainGroupViewModel : BaseViewModel<MEMGroup>
{
public abstract class BaseViewModel<T> : NotificationObject, INavigationAware
where T : Entity
{
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
{
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通常我在类构造函数中使用注册到
PropertyChanged
事件,我的 PropertyChanged 事件处理程序如下所示:
Usually I use register to the
PropertyChanged
event in the class Constructorand my PropertyChanged event handler looks like this:
我担心您实际上正在对派生类中的属性进行“手动绑定”(不好)到基类上的值(也不好)。使用继承的全部意义在于派生类可以访问基类中的内容。使用
protected
修饰符来指示事物只能由派生类访问。我建议这个(可能)更正确的方法:
基类:
派生类:
真的,订阅您正在编写的类的基类中的事件似乎令人难以置信的倒退 - 如果您使用继承而不是组合,那有什么意义呢?你要让自己平静下来吗?当事情发生时,你实际上是在要求一个对象告诉自己。为此,您应该使用方法调用。
就“当 ViewModelBase 上的一个属性发生更改时 - 我想更改我的 ViewModel 上的属性”而言,...它们是同一个对象!
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:
Derived class:
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!
订阅属性更改的直接方法是使用
INotifyPropertyChanged
如果您的BaseViewModel
实现了它:如果没有,那么它必须是
DependencyObject
,并且您的属性必须是DependencyProperties
(这可能是一种更复杂的方式)。本文介绍如何订阅 DependencyProperty 更改。
The direct way to subscribe to property changes is using
INotifyPropertyChanged
if yourBaseViewModel
implements it:If it doesn't, then it has to be a
DependencyObject
, and your properties have to beDependencyProperties
(which is probably a more complicated way).This article describes how to subscribe for
DependencyProperty
changes.