我看到一个例子,其中有2个依赖属性:
public static readonly DependencyProperty CurrentReadingProperty =
DependencyProperty.Register("CurrentReading",
typeof(double),
typeof(Gauge),
new FrameworkPropertyMetadata(Double.NaN,
FrameworkPropertyMetadataOptions.None,
new PropertyChangedCallback(OnCurrentReadingChanged),
new CoerceValueCallback(CoerceCurrentReading)
),
new ValidateValueCallback(IsValidReading)
);
并且
public static readonly DependencyProperty MinReadingProperty =
DependencyProperty.Register(
"MinReading",
typeof(double),
typeof(Gauge),
new FrameworkPropertyMetadata(
double.NaN,
FrameworkPropertyMetadataOptions.None,
new PropertyChangedCallback(OnMinReadingChanged),
new CoerceValueCallback(CoerceMinReading)
),
new ValidateValueCallback(IsValidReading));
在 OnCurrentReadingChanged 中,我执行以下操作:
d.CoerceValue(MinReadingProperty);
这将调用 CoerceValueCallback 委托 ("CoerceMinReading"),其代码如下:
private static object CoerceMinReading(DependencyObject d, object value)
{
Gauge g = (Gauge)d;
double min = (double)value;
// some required conditions;
return min;
}
我想要理解的是,为什么需要进行强制转换?
为什么不能在我的属性更改回调中直接调用 SetValue 并更改所需的属性,而不是调用 CoerceValue 并在我的 coercing 回调中处理事情呢?