Binding DataContext to ValidationRule

前端 未结 7 1922
粉色の甜心
粉色の甜心 2021-02-04 11:33

I have a custom ValidationRule that requires access to the ViewModel in order to validate a supplied value in conjunction with other properties of the ViewModel. I previously tr

7条回答
  •  说谎
    说谎 (楼主)
    2021-02-04 12:15

    After some research, I have come up with the following code which works exactly as the DataErrorValidationRule works.

    class VJValidationRule : System.Windows.Controls.ValidationRule
    {
        public VJValidationRule()
        {
            //we need this so that BindingExpression is sent to Validate method
            base.ValidationStep = System.Windows.Controls.ValidationStep.UpdatedValue;
        }
    
        public override System.Windows.Controls.ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            System.Windows.Controls.ValidationResult result = System.Windows.Controls.ValidationResult.ValidResult;
    
            System.Windows.Data.BindingExpression bindingExpression = value as System.Windows.Data.BindingExpression;
    
            System.ComponentModel.IDataErrorInfo source = bindingExpression.DataItem as System.ComponentModel.IDataErrorInfo;
    
            if (source != null)
            {
                string msg = source[bindingExpression.ParentBinding.Path.Path];
    
                result = new System.Windows.Controls.ValidationResult(msg == null, msg); 
            }
    
            return result;
        }
    

提交回复
热议问题