【发布时间】:2015-05-21 16:43:31
【问题描述】:
我看到了一个有 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 并在我的强制回调中处理事情?
【问题讨论】:
-
您永远不必这样做。也不清楚为什么你认为你确实需要这样做......
标签: c# wpf dependency-properties