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>
相关推荐
愚润求学10 分钟前
【C++】模板进阶
c语言·开发语言·c++·笔记·模板
天若有情67314 分钟前
【Python】什么是列表推导式?
开发语言·python
leslie_xin18 分钟前
(原创)[开源][.Net Framework 4.5] SimpleMVVM(极简MVVM框架)更新 v1.1,增加NuGet包
c#·wpf
xyd陈宇阳25 分钟前
C++ 入门三:函数与模板
开发语言·c++
星之卡比*25 分钟前
前端知识点---闭包(javascript)
开发语言·前端·javascript
oioihoii1 小时前
C++23新特性详解:迈向更现代化的C++
开发语言·c++·c++23
JoshuaGraham1 小时前
Java 并发-newFixedThreadPool
java·开发语言
iFlyCai1 小时前
Xcode警报“Ignoring duplicate libraries: ‘-lc++’” 警报
开发语言·c++
Freak嵌入式1 小时前
一文速通 Python 并行计算:06 Python 多线程编程-基于队列进行通信
开发语言·python·多线程·面向对象·并行计算