美文网首页
WPF使用IDataErrorInfo接口进行数据校验

WPF使用IDataErrorInfo接口进行数据校验

作者: 勿念情 | 来源:发表于2018-09-03 20:36 被阅读0次
        class ValidationBindableBase : BindableBase, IDataErrorInfo
        {
            public string this[string columnName]
            {
                get
                {
                    if (_errorMap.ContainsKey(columnName))
                    {
                        var error = _errorMap[columnName];
                        _errorMap.Remove(columnName);
    
                        return error;
                    }
                    return null;
                }   
            }
    
            public string Error => string.Join("\n",_errorMap.Values);
    
            private readonly Dictionary<string, string> _errorMap = new Dictionary<string, string>();
    
    
            protected override bool SetProperty<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
            {
                var result = base.SetProperty(ref storage, value, propertyName);
                var type = this.GetType();
                foreach (var methodInfo in type.GetMethods())
                {
                    if (methodInfo.Name == propertyName + "Validation"&& methodInfo.ReturnType == typeof(string) && methodInfo.GetParameters().Length == 0)
                    {
                        _errorMap.Add(propertyName,(string)methodInfo.Invoke(this, null));
                    }
                }
                return result;
            }
        }
    

    相关文章

      网友评论

          本文标题:WPF使用IDataErrorInfo接口进行数据校验

          本文链接:https://www.haomeiwen.com/subject/pywiwftx.html