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>
相关推荐
菜鸟~noob23314 分钟前
【电子战】第12篇:TDOA 定位——双曲线与等时差线【含matlab代码】
开发语言·matlab
零依赖极客20 分钟前
Day 9·1 KV 也量化——q8 KV 把缓存与 decode 带宽压到一半
c语言·开发语言·arm开发·人工智能·缓存·矩阵
CoderYanger26 分钟前
Java EE 进阶:2.3 JavaScript
java·开发语言·前端·javascript·css·职场和发展·java-ee
Polevne40 分钟前
C# GRPC 一元与双向流
linux·算法·c#
敲代码的嘎仔1 小时前
互动问答系统实战:两级评论模型、ES 搜索集成、Caffeine 多级缓存全记录
java·开发语言·数据库·elasticsearch·缓存·mybatis·高并发
yujunl1 小时前
找不到指定的SDK(“Microsoft.NET.Sdk.Web“)
开发语言
郝学胜-神的一滴1 小时前
C++11 工程级应用 12:编译期类型魔法,干掉重复与臃肿的代码
开发语言·数据结构·c++·软件工程·visual studio
m0_734571761 小时前
深入理解C++ 析构函数<四>虚析构函数
开发语言·c++
芒鸽1 小时前
把 Agent 运行时做成插件系统:agent-harness(openJiuwen Rust版) 的实践
开发语言·后端·rust
Brilliantwxx1 小时前
【STM32】 I2C 外设内部硬件结构和状态位
开发语言·stm32·单片机·嵌入式硬件