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>
相关推荐
Дерек的学习记录1 分钟前
Unreal Engine 5:第三人称运动系统和人物动画
开发语言·学习·ue5
Ramble_Naylor24 分钟前
Rust深度解读:异步流(Async Streams)与生成器的处理艺术
开发语言·后端·rust
努力实干32 分钟前
简单工厂模式(Simple Factory Pattern)——C++
开发语言·c++·简单工厂模式
熊猫钓鱼>_>35 分钟前
平行视界兼容模式与魔法变量配置避坑【鸿蒙心迹】
运维·服务器·开发语言·笔记·华为·harmonyos·openharmony
大鹏说大话42 分钟前
PHP 大文件上传解决方案:分片上传完整思路
开发语言·php
Wang's Blog2 小时前
Java 项目实战:交友项目 - 我的访客:需求说明
java·开发语言·交友
布莱克6052 小时前
C++ 中堆和栈的区别详解
开发语言·c++·栈·堆
像风一样自由20202 小时前
3.Dockerfile如何构建一个Python算法镜像
开发语言·人工智能·python·大模型
BuHuaX3 小时前
Lua 与 ToLua:运行机制及热更新原理
开发语言·unity·junit·c#·lua
xys_6784 小时前
深挖C++:C++入门基础
开发语言·c++