问题
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;
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?
EDIT:
The Interface implementation is as follows:
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));
}
回答1:
You're probably declaring the PropertyChangedEventHandler static.
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();
}
}
}
来源:https://stackoverflow.com/questions/50967059/raise-propertychanged-event-on-a-specific-object