问题
I've used INotifyPropertyChanged
within a custom class to fire an event when a variable has changed, but I was wondering if there was a simple way to fire an event on a single variable's change, such as a double.
For instance, in a WPF app, if I have
private double a;
in MainWindow.xaml.cs
, is there a simple way to fire the event any time a
is assigned to?
回答1:
If I understand you correctly, you need to create a Setter for a, which then fires the properychange event/custom event instead of encapsulate a
into a class.
Something like this:
private double a;
public double A
{
get { return a; }
set { a = value;
firepropertyChange(a);
}
}
回答2:
A field doesn't have any means of tracking changes. In order to make it work, it would need to be a property, and something would need to handle the tracking. That is the purpose of the INotifyPropertyChanged
interface.
The normal means of tracking changes to this value would be to implement INotifyPropertyChanged
in your class.
回答3:
Yes (depends), if you wrap your variable access through a property and fire your event on change, and make sure all access to that variable is through the property, like
private double a;
public double PropertyA
{
get
{
return a;
}
set
{
// set value and fire event only when value is changed
// if we want to know when value set is the same then remove if condition
if (a != value)
{
a = value;
PropertyChanged("PropertyA");
}
}
}
// when changing a, make sure to use the property instead...
PropertyA = 5.2;
...otherwise, no
回答4:
If you are using C# 5.0, you can employ CallerMemberName
attribute this way:
class MyData : INotifyPropertyChanged
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
RaisePropertyChanged();
}
}
private string _anotherProperty;
public string AnotherProperty
{
get { return _anotherProperty; }
set
{
_anotherProperty = value;
RaisePropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([CallerMemberName] string caller = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
}
}
As you see you just have to call RaisePropertyChanged();
in set
for each property, without typing the property names over and over.
Another approach would be to define a ModelBase
class:
class ModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void Set<T>(ref T field, T value, [CallerMemberName] string propertyName = "")
{
if (!Object.Equals(field, value))
{
field = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
And then derive your model from ModelBase
:
class Conf : ModelBase
{
NodeType _nodeType = NodeType.Type1;
public NodeType NodeType
{
get { return _nodeType; }
set { Set(ref _nodeType, value); }
}
}
来源:https://stackoverflow.com/questions/17076872/fire-event-on-value-change-of-double