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>
相关推荐
吾皇斯巴达几秒前
O_DIRECT与gcsfuse的go程序中实现内存页面对齐
开发语言·后端·golang
光电的一只菜鸡17 分钟前
高通tuning中eis需要调什么
java·开发语言·前端
兔兔兔兔119 分钟前
记录C++ 12
开发语言·c++
丰锋ff36 分钟前
基于 Qt 的智能门禁系统(三)
开发语言·qt
消费知多少1 小时前
解析勤策签约大西洋焊接费用核销实践案例
开发语言·c#
CSDN_RTKLIB1 小时前
HashSet、Dictionary
c#
曹牧1 小时前
C#与Java后台交互
java·windows·microsoft·c#
LabVIEW开发1 小时前
LabVIEW按段拆分TDMS文件的格式边界与重构
开发语言·数据库·重构·labview·labview知识·labview功能·labview程序
asdzx672 小时前
使用 Python 为 Excel 添加各类数据验证规则
开发语言·python·excel
Romantic_love_2 小时前
理解USART真实收发过程
开发语言·stm32·单片机·学习