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>
相关推荐
乾坤瞬间几秒前
【Java后端进行ai coding实践系列二】记住规范,记住内容,如何使用iflow进行上下文管理
java·开发语言·ai编程
掘金安东尼3 分钟前
Transformers.js:让大模型跑进浏览器
开发语言·javascript·ecmascript
im_AMBER21 分钟前
React 05
开发语言·前端·javascript·笔记·学习·react.js·前端框架
conkl1 小时前
在 CentOS 系统上实现定时执行 Python 邮件发送任务完整指南
linux·运维·开发语言·python·centos·mail·邮箱
whycthe1 小时前
c++竞赛常用函数
java·开发语言
wydaicls1 小时前
了解一下kernel6.12中cpu_util_cfs_boost函数的逻辑
linux·开发语言
Violet_YSWY1 小时前
final是干嘛的
java·开发语言
一只小透明啊啊啊啊2 小时前
Java的中间件
java·开发语言·中间件
学编程就要猛2 小时前
数据结构初阶:Java中的ArrayList
java·开发语言·数据结构
JH30732 小时前
10分钟理解泛型的通配符(extends, super, ?)
java·开发语言·windows