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

    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;
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容