wpf 实现接口 IDataErrorInfo 数据验证

csharp 复制代码
  public class BaseModel : BindableBase, IDataErrorInfo
  {

      public Func<object, bool> UniquenessCheck { get; set; }

      public string this[string columnName]
      {
          get
          {              
              PropertyInfo pi = this.GetType().GetProperty(columnName);

              var value = pi.GetValue(this, null);
              if (pi.IsDefined(typeof(Attrite.RequiredAttribute), true))
              {
                  if (value == null || string.IsNullOrEmpty(value.ToString()))
                      return pi.GetCustomAttribute<Attrite.RequiredAttribute>().PropName = "不能为空";
              }
             
              return string.Empty;
          }
      }

      public string Error => null;

  }
csharp 复制代码
public class UserModel : BaseModel
{
    public UserModel() { }

    private string _userName;
    [Required("不能为空")]
    public string UserName
    {
        get { return _userName; }
        set
        {
            SetProperty(ref _userName, value);
        }
    }
}
csharp 复制代码
 public class MainWindowViewModel : BindableBase
 {
     private string _title = "Prism Application";
     public string Title
     {
         get { return _title; }
         set { SetProperty(ref _title, value); }
     }

     private UserModel _user;
     public UserModel User
     {
         get { return _user; }
         set { SetProperty(ref _user, value); }
     }

     public MainWindowViewModel()
     {
         User = new UserModel();
         User.UserName = "";
     }
 }
csharp 复制代码
 <Grid>
     <TextBox x:Name="tb" Text="{Binding User.UserName, Mode=TwoWay, ValidatesOnDataErrors=True}" />
     <TextBox Text="{Binding Path=(Validation.Errors)[0].ErrorContent, ElementName=tb}" />
 </Grid>
相关推荐
凌镜icecraft1 小时前
我改文件扩展名的时候那个警告弹窗再也不会弹出来了
windows·c#·wpf·explorer
郝学胜-神的一滴1 小时前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
geovindu5 小时前
python:Logistic Regression
开发语言·后端·python·算法
摇滚侠6 小时前
《On Java 中文版 基础卷》阅读笔记 内部类 21
java·开发语言·笔记
番茄味城市甜菜6 小时前
二叉树刷题(C语言)
c语言·开发语言
布莱克6056 小时前
Swift 自动引用计数(ARC)详解:原理、循环引用与最佳实践
开发语言·ios·swift·arc·自动引用计数
FungLeo6 小时前
FengCMS·PHP+MySQL 升级实录 ·本地容器环境设计:只读挂载、LOCAL_UID、数据卷权限
开发语言·mysql·docker·php·fengcms
geovindu7 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林
真上帝的左手7 小时前
2. 编程语言-Python-Anaconda
开发语言·python