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>
相关推荐
吃好睡好便好39 分钟前
提取矩阵某一行或某一列元素
开发语言·人工智能·线性代数·算法·matlab·矩阵
deepin_sir4 小时前
10 - 函数
开发语言·python
z落落4 小时前
C#String字符串
开发语言·c#·php
猫头虎-前端技术4 小时前
JS 作用域与闭包:从变量提升到闭包陷阱的超详细解析
开发语言·javascript·云计算·bootstrap·ecmascript·openstack·perl
枫叶林FYL4 小时前
项目十:事件溯源仓储管理系统(WMS)仿真实现
开发语言·python
繁华落尽,倾城殇?5 小时前
[C++11] : atomic,nullptr,default/delete,enum class
开发语言·c++·c++11·nullptr·atomic·enum class·default/delete
01_ice5 小时前
C语言数据在内存中的存储
c语言·开发语言
代码村新手5 小时前
C++-二叉搜索树
开发语言·c++
吃好睡好便好7 小时前
创建魔方矩阵和单位矩阵
开发语言·人工智能·学习·线性代数·matlab·矩阵
影寂ldy7 小时前
C#数组的属性和方法(Clear / Copy / IndexOf )
开发语言·javascript·c#