我向名为A的DependencyProperty添加了ValidateValueCallback。现在在Validate回调中,A应与名为B的DependencyProperty的值进行比较。但是如何在静态ValidateValueCallback方法ValidateValue(对象值)中访问B的值?谢谢你的提示!
示例代码:

class ValidateTest : DependencyObject
{
    public static DependencyProperty AProperty = DependencyProperty.Register("A", typeof(double), typeof(ValidateTest), new PropertyMetadata(), validateValue);
    public static DependencyProperty BProperty = DependencyProperty.Register("B", typeof(double), typeof(ValidateTest));


    static bool validateValue(object value)
    {
        // Given value shall be greater than 0 and smaller than B - but how to access the value of B?

        return (double)value > 0 && value <= /* how to access the value of B ? */
    }
}

最佳答案

验证回调用作给定输入值相对于一组静态约束的健全性检查。在验证回调中,检查正值是验证的正确用法,但检查另一个属性则不是。如果需要确保给定值小于从属属性,则应使用property coercion,如下所示:

public static DependencyProperty AProperty = DependencyProperty.Register("A", typeof(double), typeof(ValidateTest), new PropertyMetadata(1.0, null, coerceValue), validateValue);
public static DependencyProperty BProperty = DependencyProperty.Register("B", typeof(double), typeof(ValidateTest), new PropertyMetaData(bChanged));

static object coerceValue(DependencyObject d, object value)
{
    var bVal = (double)d.GetValue(BProperty);

    if ((double)value > bVal)
        return bVal;

    return value;
}

static bool validateValue(object value)
{
    return (double)value > 0;
}

如果设置a>b(就像validationcallback那样),这不会引发异常,但实际上这是所需的行为。由于您不知道属性的设置顺序,因此应该支持以任何顺序设置属性。
我们还需要告诉wpf在b的值更改时强制属性a的值,因为强制值可能更改:
static void bChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    d.CoerceValue(AProperty);
}

07-24 09:25