小编Roh*_*jar的帖子

强制依赖属性需要什么?

我看到了一个有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)
);
Run Code Online (Sandbox Code Playgroud)

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));
Run Code Online (Sandbox Code Playgroud)

并在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;
}
Run Code Online (Sandbox Code Playgroud)

我想要理解的是,为什么我需要进行强制?

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

c# wpf dependency-properties

9
推荐指数
1
解决办法
3053
查看次数

标签 统计

c# ×1

dependency-properties ×1

wpf ×1