【问题标题】:How to do a simple validation with IDataErrorInfo and data annotations如何使用 IDataErrorInfo 和数据注释进行简单验证
【发布时间】:2018-11-29 14:14:14
【问题描述】:

我有Model 有一个属性。这个Model 继承自实现INotifyPropertyChangedIDataInfoError 的基本模型。 在我的属性上方,我有 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


    【解决方案1】:

    当您的索引器返回 null 时,位置 0 处没有 ValidationError。绑定到 (Validation.Errors).CurrentItem.ErrorContent 而不是 (Validation.Errors)[0].ErrorContent 应该可以修复绑定错误:

    <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self},
                        Path=(Validation.Errors).CurrentItem.ErrorContent}" />
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    相关资源
    最近更新 更多