如何在我的 ViewModel 中订阅 PropertyChanged 事件? [英] How do I subscribe to PropertyChanged event in my ViewModel?

查看:28
本文介绍了如何在我的 ViewModel 中订阅 PropertyChanged 事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将核心功能封装在 ViewModelBase

现在我想查看 ViewModelBase 何时引发 PropertyChanged 事件并对其采取行动.例如,当 ViewModelBase 上的一个属性发生更改时 - 我想更改我的 ViewModel 上的属性

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

我如何实现这一目标?

public class MaintainGroupViewModel : BaseViewModel<MEMGroup>
    {


public abstract class BaseViewModel<T> : NotificationObject, INavigationAware
        where T : Entity
    {

推荐答案

我担心您正在有效地将派生类中的属性手动绑定"(坏)到基类上的值(也坏的).使用继承的全部意义在于派生类可以访问基类中的内容.使用 protected 修饰符来指示事物只能被派生类访问.

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:

基类:

protected virtual void OnMyValueChanged() { }

派生类:

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.

当 ViewModelBase 上的一个属性更改时 - 我想更改我的 ViewModel 上的属性"而言,......它们是同一个对象!

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

这篇关于如何在我的 ViewModel 中订阅 PropertyChanged 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆