1

我有两个依赖属性,ValueMinVal.
我希望“Value”的默认值取决于“MinVal”。
xaml 设置的“MinVal”只有一次。
我怎样才能做到这一点?

这是代码:

    public int Value
    {
        get { return (int)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Value.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(int), typeof(NumericHexUpDown), new UIPropertyMetadata(0, ValueChanged));

    private static void ValueChanged(object sender, DependencyPropertyChangedEventArgs e)
    {

    }


    public int MinVal
    {
        get { return (int)GetValue(MinValProperty); }
        set { SetValue(MinValProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MinVal.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MinValProperty =
        DependencyProperty.Register("MinVal", typeof(int), typeof(NumericHexUpDown), new UIPropertyMetadata(0, MinValueChanged));
    private static void MinValueChanged(object sender, DependencyPropertyChangedEventArgs e)
    {

    }
4

1 回答 1

4

基本上,您将强制方法添加到您的依赖项属性中。您的默认值在元数据中。但是您希望这些值在加载 XAML 后显示之前相互反应,而强制就是这样做的。

private static void OnMinValChanged(DependencyObject d,
    DependencyPropertyChangedEventArgs e)
{
    ((NumericHexUpDown)d).CoerceValue(ValueProperty);
}
private static void OnValueChanged(DependencyObject d,
    DependencyPropertyChangedEventArgs e)
{
    ((NumericHexUpDown)d).CoerceValue(MinValProperty);
}
private static object CoerceMinVal(DependencyObject d,
    object value)
{
    double min = ((NumericHexUpDown)d).MinVal;
    return value;
}
private static object CoerceValue(DependencyObject d,
    object value)
{
    double min = ((NumericHexUpDown)d).MinVal;
    double val = (double)value;
    if (val < min) return min;
    return value;
}

元数据构造函数如下所示

public static readonly DependencyProperty MinValProperty = DependencyProperty.Register(
    "MinVal", typeof(int), typeof(NumericHexUpDown),
    new FrameworkPropertyMetadata(
            0,
            new PropertyChangedCallback(OnMinimumChanged),
            new CoerceValueCallback(CoerceMinimum)
        ),
);
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
    "Value", typeof(int), typeof(NumericHexUpDown),
    new FrameworkPropertyMetadata(
            0,
            new PropertyChangedCallback(OnValueChanged),
            new CoerceValueCallback(CoerceValue)
        ),
);

参考

于 2013-08-08T22:07:11.293 回答