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>
相关推荐
一抓掉一大把18 分钟前
MiniExcel模板填充Excel导出
开发语言·javascript·ecmascript
小红帽2.026 分钟前
开源PHP在线客服系统源码搭建教程
开发语言·开源·php
qq_433554541 小时前
C++ list代码练习、set基础概念、set对象创建、set大小操作
开发语言·c++·list
张伯毅1 小时前
Java 类型参数 T、R 、 O 、K、V 、E 、? 区别
java·开发语言
AI+程序员在路上1 小时前
单元测试与QTestLib框架使用
开发语言·c++·单元测试
哆啦A梦15882 小时前
在golang中如何将已安装的依赖降级处理,比如:将 go-ansible/[email protected] 更换为 go-ansible/@v1.1.7
开发语言·golang·ansible
张鱼小丸子_微辣2 小时前
.Net Framework 4/C# 集合和索引器
c#
布伦鸽2 小时前
C# WPF 左右布局实现学习笔记(1)
笔记·学习·c#·wpf
Teln_小凯2 小时前
Python读取阿里法拍网的html+解决登录cookie
开发语言·python·html
Tiger Z2 小时前
R 语言科研绘图第 55 期 --- 网络图-聚类
开发语言·r语言·贴图