【发布时间】:2018-11-29 14:14:14
【问题描述】:
我有Model 有一个属性。这个Model 继承自实现INotifyPropertyChanged 和IDataInfoError 的基本模型。
在我的属性上方,我有 ValidationAttribute 必填项,我想将一条错误消息带入工具提示中。
因此,我的视图中有一个文本框。
我的问题:当文本框为空时,验证有效。文本框有一个红色边框。 当文本框为空并且我在其中写入内容时,我的输出窗口中出现错误。
System.Windows.Data 错误:17:无法从“(Validation.Errors)”(类型“ReadOnlyObservableCollection`1”)获取“Item[]”值(类型“ValidationError”)。 BindingExpression:Path=(0)[0].ErrorContent;数据项='文本框'(名称='');目标元素是'TextBox'(名称='');目标属性是“工具提示”(类型“对象”) ArgumentOutOfRangeException:“System.ArgumentOutOfRangeException:指定的参数超出了有效值的范围。 参数名称:index'
重现错误: 模型
public class ModelBase : INotifyPropertyChanged, IDataErrorInfo
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string Error { get { return null; } }
public string this[string columnName]
{
get
{
var validationResults = new List<ValidationResult>();
if (Validator.TryValidateProperty(
GetType().GetProperty(columnName).GetValue(this)
, new ValidationContext(this) { MemberName = columnName }
, validationResults))
return null;
return validationResults.First().ErrorMessage;
}
}
}
public class Model : ModelBase
{
private string name;
[Required(ErrorMessage = "Wrong")]
public string Name
{
get { return name; }
set
{
name = value;
OnPropertyChanged();
}
}
}
查看
<Window.Resources>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<TextBox Margin="10" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True, Mode=TwoWay}"></TextBox>
</StackPanel>
【问题讨论】:
标签: c# wpf validation