我有两个属性,其中第一个属性(FXRate)更改时,必须更新后一个属性(CalulcatedValue).
我可以通过将CalulcatedValue设置为ReadOnly并从FXRate设置器中调用OnPropertyChanged(“ CalculatedValue”)来实现此目的.
public double FXRate {
get { return _fXRate; }
set {
Set(_fXRate, value, "FXRate");
OnPropertyChanged("CaluclatedValue");
}
}
public float CalculatedValue
{
get { return FXRate * SomeOtherValue;}
}
但是我知道CalulcatedValue属性会被调用很多(用于多个LINQ查询等).我当时考虑的是,吸气剂应该非常快地返回该值,并正计划为其提供支持.
public double FXRate
{
get { return _fXRate;}
set {
Set(_fXRate, value, "FXRate");
CalculatedValue = 0; //how to set CalculatedValue since it's setter is calculating it with its logic, i.e. the value parameter is not needed ?
}
}
private double _fXRate;
public float CalculatedValue
{
get { return _calculatedValue; }
set {
__calculatedValue = FXRate * SomeOtherValue); //consider this line takes some effort to be calculated -> instead of SomeOtherValue there might be pretty complex logic here to get the result
OnPropertyChanged("CalculatedValue");
}
}
private float _calculatedValue;
现在应如何设置CalulcatedValue?它不需要传递任何值参数,因为逻辑位于设置器内.线
CalulcatedValue=0
就是现在发生的愚蠢事情.
解决方法:
如果需要INotifyPropertyChanged通知,则将其添加到FXRate属性(和/或可能更改CalculatedValue值的任何属性)中,然后在其中进行计算:
private double _fXRate;
private float _calculatedValue;
public double FXRate
{
get { return _fXRate;}
set {
Set(_fXRate, value, "FXRate");
_calculatedValue = _fxRate * SomeOtherValue;
// this will update any control depending on the `CalculatedValue` notification
OnPropertyChanged("CalculatedValue");
}
}
public float CalculatedValue
{
get { _calculatedValue; }
}
或者,如果您希望将计算推迟到第一次读取(因为您将多次更新FxRate或实际读取CalculatedValue之前的某些操作),则可以执行以下操作:
private double _fXRate;
private float _calculatedValue;
private bool _calculatedValueIsDirty = true;
public double FXRate
{
get { return _fXRate;}
set {
Set(_fXRate, value, "FXRate");
_calculatedValueIsDirty = true;
OnPropertyChanged("CalculatedValue");
}
}
public float CalculatedValue
{
get {
if(_calculatedValueIsDirty) {
_calculatedValue = _fxRate * SomeOtherValue;
_calculatedValueIsDirty = false;
}
return _calculatedValue;
}
}
除非预先计算的值再次变脏(通过更改FXRate),否则随后对CalculatedValue的读取将很快返回.
PS:如果有类似多线程的内容,请在必要时应用锁:-)