【问题标题】:WPF Get real value from a custom validation ruleWPF 从自定义验证规则中获取真正的价值
【发布时间】:2010-11-10 06:49:57
【问题描述】:

我使用自定义验证规则来验证我的数据。但我无法访问/确定属性值。

这是我的代码

  public class MandatoryRule: ValidationRule
{
    public MandatoryRule()
    {
        ValidationStep = System.Windows.Controls.ValidationStep.UpdatedValue;
    }

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        BindingExpression exp = value as BindingExpression;

        if (value == null)
            return new ValidationResult(true, null);

        return new ValidationResult(true, null);
    }
}

我需要将 ValidationStep 设置为 UpdatedValue(用于进一步的业务逻辑)

那么问题来了:我不知道属性值是多少?因为:

  1. 它是一个通用验证器,不能绑定到特定模型
  2. Validate方法的参数值是一个BindingExpression

那么我怎样才能读懂真正的价值呢?

谢谢

【问题讨论】:

    标签: wpf data-binding


    【解决方案1】:

    最后,我想出了这个主意。

    创建一个类 DummyObject : DependencyObject。 创建一个公共静态 DependencyProperty DummyProperty。

    然后创建一个新的数据绑定,从(值为BindingExpression).ParentBinding中复制源、绑定路径、元素名称、转换器等。

    将新的数据绑定目标设置为虚拟对象。

    然后使用绑定到 UpdateTarget()

    现在您可以从 dummyproperty 访问该值。

    【讨论】:

      【解决方案2】:

      遇到同样的问题并遇到这个问题,加里的答案似乎是要走的路,但它缺少源代码。所以这是我的解释。

      public class BindingExpressionEvaluator : DependencyObject
      {
          public object Value
          {
              get { return (object)GetValue(ValueProperty); }
              set { SetValue(ValueProperty, value); }
          }
      
          public static readonly DependencyProperty ValueProperty =
              DependencyProperty.Register("ValueProperty", typeof(object), 
              typeof(BindingExpressionEvaluator), new UIPropertyMetadata(null));
      
          public static object Evaluate(BindingExpression expression)
          {
              var evaluator = new BindingExpressionEvaluator();
              var binding = new Binding(expression.ParentBinding.Path.Path);
              binding.Source = expression.DataItem;
              BindingOperations.SetBinding(evaluator,  BindingExpressionEvaluator.ValueProperty, binding);
              var value = evaluator.Value;
              BindingOperations.ClearBinding(evaluator, BindingExpressionEvaluator.ValueProperty);
              return value;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-05-20
        • 2016-12-23
        • 2017-07-25
        • 1970-01-01
        • 2016-09-23
        • 1970-01-01
        • 2017-04-11
        • 2018-02-18
        • 1970-01-01
        相关资源
        最近更新 更多