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>
相关推荐
Highcharts.js3 小时前
Highcharts漏斗图表使用配置指南
java·开发语言·javascript·信息可视化·highcharts·漏斗图
ComPDFKit9 小时前
RAG 回答只显示 PDF 文件名?用 Python 保留引用页码
开发语言·python·pdf·rag
FRing039 小时前
vue3干货总结2(vue3生命周期、父子通信、模版引用、provide和inject)
开发语言·前端·vue.js·vue3
琳少_11 小时前
java程序开发笔记
java·开发语言·数据库·笔记
七夜zippoe12 小时前
Agent 告警设计:分级告警、智能降噪与值班排班
开发语言·ai·agent·告警·智能降噪·值班排班
严肃小白兔13 小时前
PHP 8.6 正式发布:部分函数应用、原生 I/O 轮询与新特性实战解析
开发语言·php
郝学胜-神的一滴14 小时前
Effective Python 条款36:优雅拼装迭代器与生成器
开发语言·数据结构·人工智能·python·numpy·scikit-learn
wuyk55515 小时前
Python办公自动化-第04讲-批量新建Excel
开发语言·python·excel
code2cat16 小时前
【随笔】Java客户端选了HTTP/3,怎样知道请求实际走了哪个版本
java·开发语言·http
honker_X19 小时前
Python字符串全攻略:从入门到精通
开发语言·python