在特定对象上引发PropertyChanged事件 [英] Raise PropertyChanged event on a specific object
问题描述
因此,我有一个处理某些应用程序数据的类(称为DataClass).该类实现了 INotifyPropertyChanged
接口.目前,我在ViewModelBase类中创建了2个此类的静态实例(DataRx和DataTx),我想分别在每个类上引发 PropertyChanged
事件.在ViewModel上,实现为:
So i have a class (called DataClass) that handles some application data. The class implemented the INotifyPropertyChanged
interface. Currently i have 2 static instances of this class (DataRx and DataTx) that i created in the ViewModelBase class and I want to raise the PropertyChanged
events on each class separately.
On the ViewModel the implementation is:
DataRx.PropertyChanged += DataRx_PropertyChanged;
DataTx.PropertyChanged += DataTx_PropertyChanged;
问题在于,当我更改DataRx对象的任何DataClass属性时, DataRx_PropertyChanged
和 DataTx_PropertyChanged
方法均被激活,而不仅仅是 DataRx_PropertyChanged 代码>.
The issue is that while I'm changing any of the DataClass properties of DataRx object both DataRx_PropertyChanged
and DataTx_PropertyChanged
methods are activated instead of just DataRx_PropertyChanged
.
如何仅在所需对象上激活事件?
How can I activate the event just on the desired object?
接口实现如下:
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T field, T value, [CallerMemberName]string name = null)
{
if (Equals(field, value))
{
return false;
}
field = value;
OnPropertyChanged(name);
return true;
}
protected void OnPropertyChanged([CallerMemberName]string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
推荐答案
您可能是在声明PropertyChangedEventHandler静态的.
You're probably declaring the PropertyChangedEventHandler static.
INotifyPropertyChanged接口的正确实现应类似于以下内容:
The correct implementation of the INotifyPropertyChanged interface should look similar to this:
private string myProperty;
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string MyProperty
{
get
{
return myProperty;
}
set
{
if (myProperty != value)
{
myProperty = value;
NotifyPropertyChanged();
}
}
}
这篇关于在特定对象上引发PropertyChanged事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!