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>
相关推荐
fox_lht几秒前
第十四章 一个输入和输出项目:构建一个命令行程序
开发语言·后端·rust
专注VB编程开发20年3 分钟前
工控上位机开发为什么固死.net 4.5.2sdk?适配win7
python·信息可视化·c#
郑州光合科技余经理5 分钟前
海外版外卖系统:如何快速搭建国际化外卖平台
java·开发语言·前端·人工智能·小程序·系统架构·php
Cheng小攸7 分钟前
协议分析与分析工具(一)
开发语言·php
fox_lht10 分钟前
14.2.读文件
开发语言·后端·rust
codeejun10 分钟前
每日一Go-74、Go 云原生可观测性实战之OpenTelemetry 全链路采集:Trace + Metrics + Logs
开发语言·云原生·golang
神仙别闹12 分钟前
基于 Python 实现 ANN 与 KNN 的图像分类
开发语言·python·分类
yugi98783812 分钟前
基于Qt的实用二维码生成解决方案
开发语言·qt
_小许_12 分钟前
Go语言导入与导出excel文件
开发语言·golang·excel
SilentSamsara15 分钟前
高并发 API 压测与调优:locust + 火焰图 + 瓶颈定位
开发语言·python·青少年编程·docker·中间件