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

查看:89
本文介绍了如何在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天全站免登陆