【问题标题】:DependencyProperty ValidateValueCallback questionDependencyProperty ValidateValueCallback 问题
【发布时间】:2010-06-16 16:02:32
【问题描述】:

我在名为 A 的 DependencyProperty 中添加了一个 ValidateValueCallback。现在在验证回调中,应将 A 与名为 B 的 DependencyProperty 的值进行比较。但是如何在 static 中访问 B 的值ValidateValueCallback 方法 validateValue(object value)?感谢您的任何提示!

示例代码:

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 ? */
    }
}

【问题讨论】:

    标签: c# wpf validation dependency-properties


    【解决方案1】:

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

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

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

    【讨论】:

    • 非常感谢您的详细回复!标记为答案。我首先不得不习惯这种方式(不抛出异常),但好吧,似乎是“官方”方式。
    猜你喜欢
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    相关资源
    最近更新 更多