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>
相关推荐
沈韶珺1 小时前
Visual Basic语言的云计算
开发语言·后端·golang
沈韶珺1 小时前
Perl语言的函数实现
开发语言·后端·golang
嘻嘻哈哈的zl1 小时前
初级数据结构:栈和队列
c语言·开发语言·数据结构
wjs20241 小时前
MySQL 插入数据指南
开发语言
美味小鱼1 小时前
Rust 所有权特性详解
开发语言·后端·rust
Bluesonli1 小时前
第 1 天:UE5 C++ 开发环境搭建,全流程指南
开发语言·c++·ue5·虚幻·unreal engine
中游鱼2 小时前
C# 数组和列表的基本知识及 LINQ 查询
c#·linq·数组·数据处理·list数列
wjs20242 小时前
三路排序算法
开发语言
struggle20252 小时前
helm-dashboard为Helm设计的缺失用户界面 - 可视化您的发布,它提供了一种基于UI的方式来查看已安装的Helm图表
开发语言·ui·计算机视觉·编辑器·知识图谱
独自破碎E2 小时前
【4】阿里面试题整理
java·开发语言·算法·排序算法·动态规划