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>
相关推荐
存在的五月雨34 分钟前
项目中 Vitest 配置详解:vitest.config.ts
开发语言·javascript·vue.js
野犬寒鸦1 小时前
Claude Code:终端AI编程助手全指南(附带指令全讲解)
开发语言·后端·面试·ai编程
淡笑沐白1 小时前
JavaScript零基础到精通
开发语言·javascript·ecmascript
Languorous.1 小时前
C++智能指针详解:原理、使用及避坑指南
开发语言·c++
广州灵眸科技有限公司1 小时前
瑞芯微(EASY EAI)RV1126B yolov11-track多目标跟踪部署教程
linux·开发语言·网络·人工智能·yolo·机器学习·目标跟踪
呼Lu噜1 小时前
基于C#的ASP.NET Core中分析async、await的使用场景
数据库·c#·asp.net
智慧物业老杨1 小时前
智慧物业数智化转型实战:从工单响应到业主满意度的闭环构建
java·开发语言
Kiling_07041 小时前
Java集合框架:List集合详解与应用
java·开发语言·windows
fan_music2 小时前
C语言如何实现C++的类
开发语言·c++
毋语天2 小时前
Python 常用内置模块详解:日志、随机数、时间、OS 与 JSON
开发语言·python