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>
相关推荐
gugucoding11 分钟前
28. 【C语言】通用数据操作:`void *` 与类型无关编程
c语言·开发语言
曹牧13 分钟前
XML 解析过程中遇到 `org.xml.sax.SAXParseException
java·开发语言
光影少年26 分钟前
RN 架构:JS层、原生桥接层、原生渲染层 通信原理
开发语言·javascript·架构
ALex_zry42 分钟前
C++26 std::inplace_vector 详解:零堆分配的定容向量
开发语言·c++
许彰午1 小时前
77_Python数据清洗实战技巧
开发语言·python
落寞的电源1 小时前
Delegate = Object + MethodInfo
开发语言·数据库·c#
你怎么知道我是队长1 小时前
JavaScript的介绍
开发语言·javascript·ecmascript
江华森1 小时前
04-python-面向对象
开发语言·python
AI行业学习1 小时前
Notepad++ 官方纯净下载+完整安装教程(Windows)【2026.7.5】
开发语言·windows·python·前端框架·html·notepad++
前端百草阁2 小时前
JavaScript 设计模式(23 种)
开发语言·前端·javascript·设计模式