在Silverlight中添加自定义验证错误

时间:2015-05-11 13:53:24

标签: .net validation silverlight silverlight-5.0

有没有办法将自定义验证错误添加到控件的错误列表中?我知道如何使用IDataErrorInfo,INotifyErrorInfo,ValidationAttribute等,但我想从代码中添加自定义验证错误。

1 个答案:

答案 0 :(得分:0)

Found a way:

  1. First, create a public class for holding our error message:

    public class TagModelError { private readonly String errorMessage;

        public TagModelError(String errorMessage)
        {
            this.errorMessage = errorMessage;
        }
    
        public Object Tag
        {
            get
            {
                return new Object();
            }
            set
            {
                throw new ValidationException(this.errorMessage);
            }
        }
    }
    
  2. Next, create a helper method:

    public static void AddValidationError(this Control control, String errorMessage) { var expression = elm.GetBindingExpression(FrameworkElement.TagProperty);

        if (expression == null)
        {
            expression = control.SetBinding(FrameworkElement.TagProperty, new Binding("Tag")
            {               
                Mode = BindingMode.TwoWay,
                ValidatesOnExceptions = true,
                UpdateSourceTrigger = UpdateSourceTrigger.Explicit,
                Source = new TagModelError(errorMessage)
            }) as BindingExpression;
        }
    
        expression.UpdateSource();
    }
    

I am using the Tag property because it is seldom required, but you can use another one. The trick here is to cause an exception when writing back to the model.