强制依赖项属性有什么需要? [英] What is the need for Coercing a Dependency Property?

查看:84
本文介绍了强制依赖项属性有什么需要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一个示例,其中有两个依赖项属性:

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)
);

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);

and in OnCurrentReadingChanged I perform following operation d.CoerceValue(MinReadingProperty);

调用具有以下代码的CoerceValueCallback委托( CoerceMinReading):

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?

为什么我不能只在属性更改后的回调中调用SetValue并更改所需的属性,而不是调用CoerceValue并在强制回调中处理事情?

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?

推荐答案

Coercion旨在(可选)确保值在UI层可以做出此类决定的情况下有效。一个经典的例子是某种滑块控件,其中bound属性试图将值设置为超出滑块的指定范围。在这种情况下,可以将值固定为最小值或最大值而不是抛出验证异常。

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.

在SetValue属性更改期间调用SetValue效率不高,因为您可能会在递归事件中充斥整个系统。这就是为什么存在胁迫。只要记住它的限制,并在适当的地方使用它即可。在这种情况下是合适的。

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.

这篇关于强制依赖项属性有什么需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆