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>
相关推荐
kyriewen112 分钟前
Next.js:让你的React应用从“裸奔”到“穿衣服”
开发语言·前端·javascript·react.js·设计模式·ecmascript
雪飞鸿6 分钟前
ArrayPoolWrapper简洁、安全的ArrayPool
c#·.net·.net core·原创
三品吉他手会点灯7 分钟前
C语言学习笔记 - 18.C编程预备计算机专业知识 - 什么是变量
c语言·开发语言·笔记·学习
好奇龙猫12 分钟前
[大学院-python-base gammer learning2: python base programming ]
开发语言·python
海盗123431 分钟前
C#上位机开发-S7协议通信
开发语言·c#
小短腿的代码世界35 分钟前
Qt 2D 绘制实战与性能优化深度解析
开发语言·qt·性能优化
FeBaby43 分钟前
ReentrantLock 与 synchronized 底层实现对比图解
开发语言·c#
jaycyj43 分钟前
pytest
开发语言·python
A_aspectJ1 小时前
【Java基础开发】基于 Java Swing +MySQL + JDBC 版实现图书管理系统
java·开发语言·mysql
Gary Studio1 小时前
安卓HAL编译流程
开发语言·python