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>
相关推荐
feixing_fx12 小时前
原始类型与引用类型:赋值时到底复制了什么
开发语言·前端·javascript·前端框架
wuyk55512 小时前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel
zdr尽职尽责13 小时前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎
神明不懂浪漫13 小时前
【第八章】多线程(一)
java·开发语言·经验分享·笔记
yiangL_14 小时前
1、Python 输入输出实验|print 与 input 人机交互实践
开发语言·python·人机交互
山楂树の16 小时前
Java 泛型:泛型类、泛型方法、泛型接口与通配符
java·开发语言·笔记
利威尔xu16 小时前
2026-11-18-Go接口幂等设计实战
开发语言·后端·golang
eggwyw17 小时前
linux下的C\C++多进程多线程编程实例详解
开发语言·c++
布莱克60517 小时前
Swift 枚举详解:从基础语法到关联值与模式匹配
开发语言·ios·swift·枚举
布莱克60518 小时前
Swift 闭包详解:从语法到实战的完整指南
服务器·开发语言·ios·ssh·swift·闭包