WPF - 为基类实现 System.ComponentModel.INotifyPropertyChanged

2024-01-23

我想为基类上的属性实现 System.ComponentModel.INotifyPropertyChanged 接口,但我不太确定如何连接它。

以下是我想要接收通知的属性的签名:

public abstract bool HasChanged();

我在基类中处理更改的代码:

public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(String info)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(info));
    }
}

如何处理基类中事件的连接,而不必在每个子类中调用 OnPropertyChanged() ?

Thanks,
Sonny

编辑: 好的...所以我认为当 HasChanged() 的值发生变化时,我应该调用OnPropertyChanged("HasChanged"),但我不确定如何将其放入基类中。有任何想法吗?


这就是你所追求的吗?

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    //make it protected, so it is accessible from Child classes
    protected void OnPropertyChanged(String info)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(info));
        }
    }

}

请注意,OnPropertyChanged 可访问级别受到保护。然后在您的具体班级或子班级中,您可以:

public class PersonViewModel : ViewModelBase
{

    public PersonViewModel(Person person)
    {
        this.person = person;
    }

    public string Name
    {
        get
        {
            return this.person.Name;
        }
        set
        {
            this.person.Name = value;
            OnPropertyChanged("Name");
        }
    }
}

编辑:再次阅读OP问题后,我意识到他不想打电话OnPropertyChanged在儿童班级中,所以我很确定这会起作用:

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private bool hasChanged = false;
    public bool HasChanged
    {
        get
        {
            return this.hasChanged;
        }
        set
        {
            this.hasChanged = value;
            OnPropertyChanged("HasChanged");
        }
    }

    //make it protected, so it is accessible from Child classes
    protected void OnPropertyChanged(String info)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(info));
        }
    }
}

在儿童班:

public class PersonViewModel : ViewModelBase
{
    public PersonViewModel()
    {
        base.HasChanged = true;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WPF - 为基类实现 System.ComponentModel.INotifyPropertyChanged 的相关文章

随机推荐