手动设置控件上的验证消息

问题描述:

我试图手动设置验证消息,而没有您抛出异常的常见做法。手动设置控件上的验证消息

我知道我可以手动更改控件的状态如下:

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

现在我只是想手动设置错误信息......任何人都知道怎么样?

我知道这是一个HACK,但这是我现在需要的东西。

任何想法???

+0

你能告诉代码或者在你的错误信息是如何建立更具体的?有很多方法可以在XAML中进行验证 – 2010-11-12 17:34:26

+0

恐怕我还是不明白你是如何设置errormessage的。例如,您可以在ErrorTemplate中包含文本块,并将errorResponse对象传递给错误消息。但是,这听起来不像你采取的路线。我需要了解什么“元素”显示错误消息(textblock,label,msgbox),然后才能帮助您设置它。 – 2010-11-12 23:28:09

这里是一个解决方案....找到this后。

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

//辅助类

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

嘿,谢谢你帮我解决这个问题。关于如何在Silverlight中进行高级工作的教程存在大量缺乏。同样不幸的是,Silverlight论坛的每一个链接似乎都不再起作用。 – cost 2013-12-27 07:19:44