【问题标题】:DataAnnotations Validation in MVVM is not workingMVVM 中的 DataAnnotations 验证不起作用
【发布时间】:2016-01-05 10:50:09
【问题描述】:

验证不起作用的可能原因是什么?

public class DatabaseObj : ValidatableModel, IFormattable
{
    [Required(ErrorMessage="Hostname is required")]
    public string Hostname
    {
        get { return _hostname; }
        set { SetProperty(ref _hostname, value); }
    }
}

[Serializable]
public abstract class ValidatableModel : Model, INotifyDataErrorInfo
{
}

[Serializable]
public abstract class Model : INotifyPropertyChanged
{
}

在 xaml 中,

<TextBox Text="{Binding DatabaseObj.Hostname, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=true, NotifyOnValidationError=true}" 
             Grid.Column="1" Grid.Row="1" Margin="0,1,91,10" HorizontalAlignment="Stretch"/>

但是,当我编译和运行时,我清空了文本框,没有显示错误消息,颜色仍然保持不变。

*对象类更新

【问题讨论】:

标签: c# wpf xaml


【解决方案1】:

WPF 中没有对 DataAnnotations 的默认支持。在 WPF 中实现验证有两种方法。

  1. 使用基于异常的验证。在数据绑定表达式中,您可以打开异常验证,如下面的代码所示:

    <TextBox Name=«age» Grid.Row=«1» Grid.Column=«1» Width=«200» Margin=«5» Text="{Binding Path=Age, ValidatesOnExceptions=true, NotifyOnValidationError=true, UpdateSourceTrigger=PropertyChanged}" />
    

    然后,在您的模型中,您可以使用数据类型的默认逻辑,它会验证输入值(例如,它会阻止为 Int32 类型设置非数字值)。或者您可以使用属性设置器中的异常来添加您的自定义逻辑:

    public int Age 
    { 
        get { return age; }
        set
        {
            if(value < 0)
                throw new ArgumentException("Age can't be less then zero");
            if(value > 30)
                throw new ArgumentException("Huh, no, too old for me");
            age = value;
            OnNotifyPropertyChanged();
        }
    }
    
  2. 在您的班级中实施IDataErrorInfoMSDN 上有指南。

    public string Error
    {
        get
        {
            return null;
        }
    }
    
    public string this[string name]
    {
        get
        {
            string result = null;
    
            if (name == "Age")
            {
                if (this.age < 0)
                {
                    result = "Age can't be less then zero";
                }
                if(this.age > 30)
                {
                    result = "Huh, no, too old for me";
                }                   
            }
            return result;
        }
    }
    

互联网上有很多文章(12)可以使用 DataAnnotations 进行验证,然后您可以从这些文章中添加包并修改您的代码以实现您的场景。

【讨论】:

    猜你喜欢
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多