gpt4 book ai didi

c# - DependencyProperty ValidateValueCallback 问题

转载 作者:太空狗 更新时间:2023-10-29 18:17:08 27 4
gpt4 key购买 nike

我向名为 A 的 DependencyProperty 添加了一个 ValidateValueCallback。现在在验证回调中,应将 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 ? */
}
}

最佳答案

验证回调用于针对一组静态约束对给定输入值进行健全性检查。在您的验证回调中,检查正值是正确使用验证,但检查另一个属性则不是。如果需要确保给定值小于依赖属性,则应使用 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);
}

关于c# - DependencyProperty ValidateValueCallback 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3055058/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com