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>
相关推荐
hez20102 小时前
TypedSql:在 C# 类型系统上实现一个 SQL 查询引擎
c#·.net·.net core·compiler
胡萝卜3.03 小时前
掌握C++ map:高效键值对操作指南
开发语言·数据结构·c++·人工智能·map
电子_咸鱼3 小时前
【STL string 全解析:接口详解、测试实战与模拟实现】
开发语言·c++·vscode·python·算法·leetcode
世洋Blog4 小时前
利用<<左移运算符优雅的设计游戏能力的任意组合和判断
游戏·unity·c#
沐知全栈开发4 小时前
ionic 选项卡栏操作详解
开发语言
曹牧4 小时前
C#中,#region和#endregion
开发语言·c#
顾安r4 小时前
11.22 脚本打包APP 排错指南
linux·服务器·开发语言·前端·flask
czhc11400756634 小时前
c# 1121 构造方法
java·javascript·c#
蒙小萌19935 小时前
Swift UIKit MVVM + RxSwift Development Rules
开发语言·prompt·swift·rxswift
Z***25805 小时前
Java爬虫框架
java·开发语言·爬虫