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>
相关推荐
wuyoula6 分钟前
尹之盾企业版网络验证
服务器·开发语言·javascript·c++·人工智能·ui·c#
Via_Neo11 分钟前
区间dp算法
开发语言·javascript·算法
aq553560015 分钟前
Laravel 10.x重磅升级:PHP 8.1+新时代
开发语言·php·laravel
秋雨梧桐叶落莳21 分钟前
iOS——Masonry约束内容整理
开发语言·学习·macos·ios·objective-c·cocoa
Hesionberger22 分钟前
LeetCode72.编辑距离(多维动态规划)
java·开发语言·c++·python·算法
Via_Neo30 分钟前
Bash Game
开发语言·bash
zdr尽职尽责1 小时前
Untiy 处理Aseprite 资产 解决偏移问题
学习·unity·c#·游戏引擎
菜菜的顾清寒1 小时前
C++面试题自用-持续更新
开发语言·c++
t***5441 小时前
如何在 Dev-C++ 中使用 Clang 调试
开发语言·c++
c++之路1 小时前
C++ 重载函数、运算符重载、抽象类(接口)
开发语言·c++