gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:42:48 25 4
gpt4 key购买 nike

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

这是我希望收到通知的属性的签名:

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()?

谢谢,
桑尼

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

最佳答案

这就是你想要的吗?

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

关于c# - WPF - 为基类实现 System.ComponentModel.INotifyPropertyChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4289418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com