WPF 将 ViewModel 属性传递给 Validation

标签 wpf validation viewmodel arguments

我必须遵循 xaml 中对validationRules 的调用,并且我想将 View 模型(位于数据上下文中)属性作为参数传递。我怎样才能实现这一目标?

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

最佳答案

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

不幸的是,它只有在更新绑定(bind)源后才有效。


这是一个例子:

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;
    }
}

关于WPF 将 ViewModel 属性传递给 Validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10985206/

相关文章:

c# - WPF 将一个控件的启用属性绑定(bind)到 CheckBox

wpf - 如何: Create reminders that should trigger an event to be handled in a Windows application?

c# - WPF,XML 数据绑定(bind)到依赖/级联组合框

c# - 在 WPF 文本框上调用 Select() 不执行任何操作

javascript - 没有脚本标签与服务器端验证?

ios - 查看模型依赖注入(inject)

c# - ViewModel 可以具有 IEnumerable<> 类型的属性而不是 Array

java - Apache UrlValidator 认为 URL 无效

Spring Validation 自定义消息 - 字段名称

c# - ListView 中 MVC 5 的下拉列表(Viewmodel 的 IEnumerable)