开发者

Set Validation Message on Control Manually

I am trying to set the Validation Message manually without the common practice where you throw an exception.

I know I can manually change the state of the control as follows:

VisualStateManager.GoToState(this.TextBox, "InvalidFocused", true);

Now I just want to set the 开发者_StackOverflow中文版error message manually... Anyone know how?

I know this is a HACK but it's something I need at this point.

Any ideas???


Here is a solution....found this post.

public object Value
{
   get { return (object)GetValue(ValueProperty); }
   set 
   {
      if (value.ToString() == "testing")
      {
          SetControlError(this, "This is an invalid value.");
      }
      else
      {
          ClearControlError(this);
          SetValue(ValueProperty, value);
      }
   }
}

public void ClearControlError(Control control)
{
   BindingExpression b = control.GetBindingExpression(Control.TagProperty);

   if (b != null)
   {
      ((ControlValidationHelper)b.DataItem).ThrowValidationError = false;
      b.UpdateSource();
   }
}       


 public void SetControlError(Control control, string errorMessage)
 {
    ControlValidationHelper validationHelper =
                new ControlValidationHelper(errorMessage);

    control.SetBinding(Control.TagProperty, new Binding("ValidationError")
    {
       Mode = BindingMode.TwoWay,
       NotifyOnValidationError = true,
       ValidatesOnExceptions = true,
       UpdateSourceTrigger = UpdateSourceTrigger.Explicit,
       Source = validationHelper
    });

    // this line throws a ValidationException with your custom error message;
    // the control will catch this exception and switch to its "invalid" state
    control.GetBindingExpression(Control.TagProperty).UpdateSource();
}

// Helper Class

using System.ComponentModel.DataAnnotations;
public class ControlValidationHelper
{
    private string _message;

    public ControlValidationHelper(string message)
    {
        if (message == null)
        {
            throw new ArgumentNullException("message");
        }

        _message = message;
        ThrowValidationError = true;
    }

    public bool ThrowValidationError
    {
        get;
        set;
    }

    public object ValidationError
    {
        get { return null; }
        set
        {
            if (ThrowValidationError)
            {
                throw new ValidationException(_message);
            }
        }
    }
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜