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>
相关推荐
利威尔xu1 小时前
Go channel 关闭 3 个 panic:向已关闭 channel 发送,服务当场崩溃
开发语言·后端·golang·并发编程·channel
山楂树の1 小时前
Java BigDecimal笔记
java·开发语言
Java展博5 小时前
[Go 后端转场] 从 try-catch 到 if err != nil:写惯 Java 的人第一次上手最别扭的 4 件事
java·开发语言·golang
SEO_juper5 小时前
Node.js 全站 SEO 体检报告生成器:一次查完标题、描述、canonical、H1、图片
开发语言·前端·node.js·html·bash
风落青芜5 小时前
数据结构:堆的概念与实现
c语言·开发语言·数据结构·算法
H H.8 小时前
Java企业级开发:从框架到工程化实战
java·开发语言·经验分享·其他·课程设计
吃我一窝jio20 小时前
Python与Go线程模型深度对比
java·开发语言·python
eggwyw20 小时前
C++ union 的一种妙用法
开发语言·c++
何以解忧唯有撸码1 天前
开源】当桌面图标开始打台球:我用 WinForms 做了一桌“真的”台球
c#·winform·自定义控件·gdi
starzy19901 天前
深入理解Scala隐式函数:自动类型转换
开发语言·后端·scala