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>
相关推荐
雨田言炎22 分钟前
四、关于Qt项目需要知道的
开发语言·笔记·qt
猿长大人38 分钟前
C# | JSON 序列化中的多态接口处理:基于 Attribute 实现精准 $type 控制
c#·json
程序喵大人1 小时前
【C++进阶】STL算法与函数对象 - 02 sort为什么需要随机访问迭代器
开发语言·c++·算法
SomeB1oody1 小时前
【RustyML入门】2.6. 线性判别分析
开发语言·后端·机器学习·rust·教程
用户昵称1002 小时前
C/C++编程-工程实践-本地存储log的工程意义
c语言·开发语言
吹什么轩3 小时前
c++复习:map和set的使用
开发语言·c++
必须得开心呀4 小时前
qt生成dump文件并定位异常
开发语言·qt
fpcc4 小时前
跟我学C++中级篇—内存流
开发语言·c++
Cicada1284 小时前
ccvt:一个用 Rust 写的中国地图坐标系互转命令行工具
开发语言·后端·rust