问题
I saw an example where there were 2 dependency properties:
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)
);
and
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));
and in OnCurrentReadingChanged I perform following operation
d.CoerceValue(MinReadingProperty);
which invokes CoerceValueCallback delegate ("CoerceMinReading") which has following code:
private static object CoerceMinReading(DependencyObject d, object value)
{
Gauge g = (Gauge)d;
double min = (double)value;
// some required conditions;
return min;
}
What I want to understand is, why do I need to perform coercion?
Why can't I just call SetValue inside my property changed callback and change required properties instead of calling CoerceValue and handling things in my coerce callback?
回答1:
Coercion is designed to (optionally) make sure a value is valid in situations where it is alright for the UI layer to make such decisions. A classic example is some sort of slider control where a bound property is trying to set the value out of the specified range of the slider. In this case it is acceptable to 'clamp' the value ito it's minimum or maximum rather than throwing validation exceptions.
Calling SetValue during a SetValue property change is not efficient because you are potentially flooding the system with recursive events. This is why coercion exists. Just bear in mind its limits and use it where appropriate. In this case it is appropriate.
来源:https://stackoverflow.com/questions/30379687/what-is-the-need-for-coercing-a-dependency-property