DependencyProperty ValidateValueCallback问题

ste*_*wpf 8 c# validation wpf dependency-properties

我在一个名为A的DependencyProperty中添加了一个ValidateValueCallback.现在在validate回调中,A应该与一个名为B的DependencyProperty的值进行比较.但是如何在静态 ValidateValueCallback方法中访问B的值validateValue(对象值)?谢谢你的提示!

示例代码:

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 ? */
    }
}
Run Code Online (Sandbox Code Playgroud)

Abe*_*cht 15

验证回调用作针对一组静态约束的给定输入值的健全性检查.在验证回调中,检查正值是否正确使用验证,但不检查另一个属性.如果您需要确保给定值小于依赖属性,则应使用属性强制,如下所示:

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

虽然如果设置A> B(如ValidationCallback那样),这不会引发异常,但这实际上是所需的行为.由于您不知道属性的设置顺序,因此您应该支持按任何顺序设置的属性.

如果B的值发生变化,我们还需要告诉WPF强制属性A的值,因为强制值可能会改变:

static void bChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    d.CoerceValue(AProperty);
}
Run Code Online (Sandbox Code Playgroud)