Passing state of WPF ValidationRule to View Model in MVVM

前端 未结 9 1716
难免孤独
难免孤独 2021-01-01 20:10

I am stuck in a seemingly common requirement. I have a WPF Prism (for MVVM) application. My model implements the IDataErrorInfo for validation. The

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-01 20:44

    Since .NET 4.5, ValidationRule has an overload of the Validate method:

    public ValidationResult Validate(object value, CultureInfo cultureInfo,
        BindingExpressionBase owner)
    

    You can override it and get the view model this way:

    public override ValidationResult Validate(object value, 
        CultureInfo cultureInfo, BindingExpressionBase owner)
    {
        ValidationResult result = base.Validate(value, cultureInfo, owner);
        var vm = (YourViewModel)((BindingExpression)owner).DataItem;
        // ...
        return result;
    }
    

提交回复
热议问题