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>
相关推荐
糯米导航25 分钟前
Rust + ONNX Runtime 构建生产级 AI 推理服务:从零到压测
开发语言·人工智能·rust
阿pin37 分钟前
Java随笔-ConcurrentHashMap
java·开发语言·哈希算法
秋田君1 小时前
QT_QT布局详解
开发语言·数据库·qt
ximen502_1 小时前
Python 语言知识总结
开发语言·python
m0_738120721 小时前
PHP代码审计基础——超全局变量(三)
开发语言·安全·网络安全·php
烟锁池塘柳01 小时前
【C/C++】解决C++控制台输出中文乱码问题
c语言·开发语言·c++
C+-C资深大佬1 小时前
Java 变量:从入门到精通
java·开发语言·python
辞旧 lekkk1 小时前
【Qt系统相关】鼠标事件
linux·开发语言·qt·学习·计算机外设·萌新
chouchuang2 小时前
day-027-面向对象-下
开发语言·python
誰能久伴不乏2 小时前
C++11 随机数生成——告别 rand()
开发语言·c++