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>
相关推荐
栗子~~4 分钟前
Python实战- Milvus 向量库 使用相关方法demo
开发语言·python·milvus
狐凄6 分钟前
Python实例题:基于 Flask 的在线聊天系统
开发语言·python
狐凄7 分钟前
Python实例题:基于 Flask 的任务管理系统
开发语言·python
小老鼠爱大米19 分钟前
[C#] WPF - 资源URI
c#·wpf·uri
shootero@126.com23 分钟前
R语言开发记录,一
开发语言·r语言
勤奋的知更鸟27 分钟前
Java 编程之状态模式
java·开发语言·状态模式
沐知全栈开发35 分钟前
R 列表:深入解析与高效应用
开发语言
爱喝茶的小茶37 分钟前
周赛98补题
开发语言·c++·算法
Whoisshutiao1 小时前
Python网安-zip文件暴力破解(仅供学习)
开发语言·python·网络安全
ComputerInBook2 小时前
C++ 标准模板库算法之 transform 用法
开发语言·c++·算法·transform算法