当 TextBox 为空时,我有一个简单的验证来显示错误消息。问题在于消息仅显示消息的第一个字母。
在文本框样式中:
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip" Value="{Binding Path=(Validation.Errors)[0].ErrorContent, RelativeSource={x:Static RelativeSource.Self}}" />
</Trigger>
如果我将错误消息直接设置为 Setter Value,它会毫无问题地显示所有内容。
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip" Value="This field is required!" />
</Trigger>
XAML 代码:
<TextBox Text="{Binding Name, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged,
ValidatesOnNotifyDataErrors=True,
NotifyOnValidationError=True}" />
C# 代码
private readonly Dictionary<string, string> _errors = new Dictionary<string, string>();
private readonly object _lock = new object();
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public IEnumerable GetErrors(string propertyName)
{
string errorsForName;
lock (_lock)
{
errorsForName = _errors.FirstOrDefault(e => e.Key == propertyName).Value;//.TryGetValue(propertyName, out errorsForName);
}
return errorsForName;
}
public bool HasErrors
{
get { return _errors.Values.FirstOrDefault(l => !String.IsNullOrEmpty(l)) != null; }
}
private void RaiseErrorsChanged(string propertyName)
{
EventHandler<DataErrorsChangedEventArgs> handler = ErrorsChanged;
if (handler == null) return;
var arg = new DataErrorsChangedEventArgs(propertyName);
handler.Invoke(this, arg);
}
private void RequiredValidation(string propertyName, string value)
{
lock (_lock)
{
if (String.IsNullOrWhiteSpace(value))
{
_errors[propertyName] = "The name can't be null or empty.";
}
else
{
if (_errors.ContainsKey(propertyName)) { _errors.Remove(propertyName); }
}
RaiseErrorsChanged(propertyName);
SaveCommand.RaiseCanExecuteChanged();
}
}