WPF将ViewModel属性传递给Validation

时间:2012-06-11 18:02:24

标签: wpf validation viewmodel arguments

我必须跟随xaml中的调用验证规则,并且我希望将viewmodel(即在datacontext中)属性作为参数传递。我怎么能得到那个?

                    <Binding.ValidationRules>
                        <vm:RiskCodeValidation/>
                    </Binding.ValidationRules> 

2 个答案:

答案 0 :(得分:3)

如果将ValidationRule.ValidationStep设置为ValidationStep.CommitedValue或ValidationStep.UpdatedValue,则Validate方法中的value参数将为BindingExpression类型,您可以使用BindingExpression.DataItem属性获取DataContext。

不幸的是,它仅在更新绑定源后才有效。


以下是一个例子:

public class RiskCodeValidation : ValidationRule
{
    public RiskCodeValidation()
        : base(ValidationStep.CommittedValue, true)
    {
    }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        var expression = value as BindingExpression;
        if (expression != null)
        {
            var sourceItem = expression.DataItem;
            if (sourceItem != null)
            {
                var propertyName = expression.ParentBinding != null && expression.ParentBinding.Path != null ? expression.ParentBinding.Path.Path : null;
                var sourceValue = sourceItem.GetType().GetProperty(propertyName).GetValue(sourceItem, null);

                // TODO: do validation logic based on sourceItem, propertyName and sourceValue.
            }
        }

        return ValidationResult.ValidResult;
    }
}

答案 1 :(得分:0)

我打算知道WPF ValidationRules的限制。我无法绑定依赖属性做ValidationRules的属性。这里解释并解决了这个问题(由于WPF的限制,仍然是丑陋的解决方案):

http://michlg.wordpress.com/2010/01/29/wpf-custom-validationrule-with-an-additional-parameter/

http://www.codeproject.com/Articles/18678/Attaching-a-Virtual-Branch-to-the-Logical-Tree-in

http://www.11011.net/wpf-binding-properties

或者只是使用System.ComponentModel.IDataErrorInfo - 现在就跟着这个。