DependencyProperty ValidateValueCallback问题

时间:2010-06-16 16:02:33

标签: c# wpf validation dependency-properties

我在一个名为A的DependencyProperty中添加了ValidateValueCallback。现在在validate回调中,A应该与名为B的DependencyProperty的值进行比较。但是如何在 static 中访问B的值ValidateValueCallback方法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 ? */
    }
}

1 个答案:

答案 0 :(得分:15)

验证回调用作针对一组静态约束的给定输入值的健全性检查。在验证回调中,检查正值是否正确使用验证,但不检查另一个属性。如果您需要确保给定值小于依赖属性,则应使用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&gt;这不会引发异常。 B(就像ValidationCallback一样),这实际上是理想的行为。由于您不知道属性的设置顺序,因此您应该支持按任何顺序设置的属性。

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

static void bChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    d.CoerceValue(AProperty);
}