我正在尝试手动设置验证消息,而不进行抛出异常的常规做法。
我知道我可以手动更改控件的状态,如下所示:
VisualStateManager.GoToState(this.TextBox, "InvalidFocused", true);
现在我只想手动设置错误消息......任何人都知道怎么做?
我知道这是一个HACK,但这是我现在需要的东西。
任何想法???
答案 0 :(得分:1)
这是一个解决方案....发现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();
}
// 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);
}
}
}
}