首页 > 其他分享 >WPF Validation - Using INotifyDataErrorInfo | .NET Land (kmatyaszek.github.io)

WPF Validation - Using INotifyDataErrorInfo | .NET Land (kmatyaszek.github.io)

时间:2023-03-09 18:55:05浏览次数:56  
标签:GetErrors Land propertyName github INotifyDataErrorInfo property errors validati

WPF Validation - Using INotifyDataErrorInfo | .NET Land (kmatyaszek.github.io)

In the .NET 4.5 was introduced new interface INotifyDataErrorInfo which enables data entity classes to implement custom validation rules and expose validation results asynchronously. This interface has three members:

  • HasErrors property indicates whether there are any validation errors
  • GetErrors method returns an IEnumerable that contains validation errors for the specified property (when the propertyName parameter isn’t equal to null or empty string) or for the entire entity (when the propertyName parameter is equal to null or empty string)
  • ErrorsChanged event must occur when the validation errors have changed for a property or for the entity

As GetErrors returns IEnumerable you can return multiple errors per property. Also, you can return custom error object (this is not possible using IDataErrorInfo interface). As you can see this new interface provides more flexible validation model in WPF. By default, ValidatesOnNotifyDataErrors is set to true so you don’t have to set this explicit in the binding expression. Below you can see the result of my example program (as you can see TextBox has two errors).

Below you can see an example implementation of the INotifyDataErrorInfo:

public class MainViewModel : BindableBase, INotifyDataErrorInfo
{
    private string _userName;
    private readonly Dictionary<string, List<string>> _errorsByPropertyName = new Dictionary<string, List<string>>();

    public MainViewModel()
    {
        UserName = null;
    }

    public string UserName
    {
        get => _userName;
        set
        {
            _userName = value;
            ValidateUserName();
            RaisePropertyChanged();
        }
    }

    public bool HasErrors => _errorsByPropertyName.Any();

    public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

    public IEnumerable GetErrors(string propertyName)
    {
        return _errorsByPropertyName.ContainsKey(propertyName) ?
            _errorsByPropertyName[propertyName] : null;
    }

    private void one rrorsChanged(string propertyName)
    {
        ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
    }

    private void ValidateUserName()
    {
        ClearErrors(nameof(UserName));
        if (string.IsNullOrWhiteSpace(UserName))
            AddError(nameof(UserName), "Username cannot be empty.");
        if (string.Equals(UserName, "Admin", StringComparison.OrdinalIgnoreCase))
            AddError(nameof(UserName), "Admin is not valid username.");
        if (UserName == null || UserName?.Length <= 5)
            AddError(nameof(UserName), "Username must be at least 6 characters long.");
    }

    private void AddError(string propertyName, string error)
    {
        if (!_errorsByPropertyName.ContainsKey(propertyName))
            _errorsByPropertyName[propertyName] = new List<string>();

        if (!_errorsByPropertyName[propertyName].Contains(error))
        {
            _errorsByPropertyName[propertyName].Add(error);
            one rrorsChanged(propertyName);
        }
    }

    private void ClearErrors(string propertyName)
    {
        if (_errorsByPropertyName.ContainsKey(propertyName))
        {
            _errorsByPropertyName.Remove(propertyName);
            one rrorsChanged(propertyName);
        }
    }
}

And below snippet of code shows you how you can show to user multiple errors to single property:

<TextBox Text="{Binding UserName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}">
    <Validation.ErrorTemplate>
        <ControlTemplate>
            <StackPanel>
                <AdornedElementPlaceholder x:Name="textBox" />
                <ItemsControl ItemsSource="{Binding}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding ErrorContent}" Foreground="Red" />
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </ControlTemplate>
    </Validation.ErrorTemplate>
</TextBox>

A complete example is available on the following link: https://github.com/kmatyaszek/WPFValidationINotifyDataErrorInfo

 

WPF validation using INotifyDataErrorInfo - Dot Net For All

In this article I will discuss about INotifyDataErrorInfo which is used to validate the data asynchronously in WPF. In my previous articles I have discussed about the ways to validate data entered in the UI.

Please find the previous articles link below

Validation using INotifyDataErrorInfo

  • Added in .NET 4.5 for WPF
  • It works on the same principle as IDataErrorInfo but it is based on the event driven mechanism which notifies for the validation errors asynchronously based on the input from some time consuming operation like service call. It will wait for the results to come back and eventually it will raise the event.
  • Set ValidatesOnNotifyDataErrors=True on binding.
  • Binding will call the GetErrors method of the INotifyDataErrorInfo when the property is set in the ViewModel through view.
  • Binding also subscribes to the ErrorsChanged event in the interface.
  • If the ErrorsChanged event is raised, it will go and re query the GetErrors method for the property for which the event is raised.
  • To implement this we need to manage a dictionary of errors per property as part of error.
  • One of the advantage of this over IDataErrorInfo is that we can return multiple errors per property.

 

The interface has three members which the derived class need to implement. Whenever we are setting this validation, the HasErrors property is called by the binding which in turn calls the GetErrors method to return the error if the HasErrors return true. After some point when GetErrors is called the ErrorsChanged event is raised and it again calls GetErrors method. It is assuming that there are some asynchronous operation that filled the collection on which the GetErrors is working on.

As we can see the GetErrors method return the IEnumerable object. It means that it is working on some collection of the objects to get the errors.

 

标签:GetErrors,Land,propertyName,github,INotifyDataErrorInfo,property,errors,validati
From: https://www.cnblogs.com/chucklu/p/17201072.html

相关文章

  • GOLAND-激活码-20230309
    33MEHOB8W0-eyJsaWNlbnNlSWQiOiIzM01FSE9COFcwIiwibGljZW5zZWVOYW1lIjoiUG9saXRla25payBNZXJsaW1hdSBNZWxha2EiLCJhc3NpZ25lZU5hbWUiOiJtYWdnaWUgc2VyIiwiYXNzaWduZWVFbWFp......
  • Git 上传项目至 GitHub 全过程
    一、问题引入在Git上传项目至GitHub过程中,出现了一些意想不到的情况,所以有必要记录一次全过程。诸如此类的问题有:1)RPCfailederror:RPCfailed;HTTP408curl22......
  • Github从入门到实操
    Git基础创建版本库gitinit添加及提交到仓库gitaddxxx.filegitcommit-m"xxxx"##看看工作区和暂存区的区别gitdiffxxx.file版本回退#查看最近三次co......
  • fatal: unable to access 'https://github.com/nhn/raphael.git/': OpenSSL SSL_read:
    这个问题真的处理了一上午的时间才解决,具体怎么解决的我也不是很清楚,大致步骤是这样的。由于公司要升级项目,所以找了好多轮子来学习。然后在准备学习这个轮子的时候在安装......
  • 使用Hexo+Github搭建免费个人博客过程记录
    虽然n久没有用GitHub了,记录一下个人博客怎么弄安装前提安装Hexo相当简单,只需要先安装下列应用程序即可:Node.js(安装最新版本即可,npm也一块装好了)npm-v测试Git前期......
  • .NET Github Actions 测试覆盖率
    如果熟悉GIthub我们经常可以在一些开源项目的PR上看到会配置测试的验证以及覆盖率的报告,并且可以强制覆盖率不低于设定的值才可以进行MergePR。1.测试创建一个xU......
  • GitHub存储库里查找敏感数据
    GitHub存储库里查找敏感数据一些源代码搜索平台https://github.com/search?type=code&auto_enroll=truehttps://docs.gitlab.com/ee/user/search/advanced_search.html......
  • Github 托管 Hugo
    详情hugo:官网地址Go-lang:官网地址Git:官网地址辅助工具->GithubProxy:官网地址......
  • git上传github
    三个区域:代码所在工程文件夹,在前者之上抽象的本地仓库git,在遥远的远程仓库github/gitee/gitlab等 上传步骤工程文件夹gitbash:gitinit初始化为仓库gitclone......
  • Github TOC生成
    生成Github目录Toc1.利用VSCode【MarkdownAllinOne】插件1.1预览:Ctrl+k后,按下V1.2目录生成安装插件时,要选择Trust,否则在命令行中找不到相关命令在......