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>
相关推荐
lly20240627 分钟前
《jEasyUI 取得选中行数据》
开发语言
Ulyanov1 小时前
《从质点到位姿:基于Python与PyVista的导弹制导控制全栈仿真》: 刚体觉醒——6-DOF刚体动力学、四元数与全姿态解算
开发语言·人工智能·python·算法·系统仿真·雷达电子对抗仿真
nexustech1 小时前
JavaScript日期处理工具date-fns,累计36.5k Star
开发语言·javascript·其他·ecmascript
Sylvia33.1 小时前
足球数据API接入实战:从认证到实时比分推送的完整指南
java·开发语言·前端·c++·python
Chloeis Syntax1 小时前
JavaEE初阶学习日记(1)---线程和进程
java·开发语言·学习·线程·javaee
凯瑟琳.奥古斯特1 小时前
SpringBoot快速入门指南
java·开发语言·spring boot·后端·spring
江屿风2 小时前
【c++笔记】类和对象流食般投喂(上)
开发语言·c++·笔记
xyq20242 小时前
Lua 模块与包
开发语言
小短腿的代码世界2 小时前
打印不止是QPrinter:深入Qt Print Support框架的内核设计与跨平台输出管道
开发语言·qt
性野喜悲2 小时前
python将excel中的链接转成图片并替换链接展示在excel中【将pdf的第一页插入excel并将对应信息获取到插入签名等位置】
开发语言·python·excel