From 40e3e4d5bee00db74b70e3fafe381ad6b0d99202 Mon Sep 17 00:00:00 2001 From: Tim Date: Thu, 4 Jun 2020 10:02:03 +0200 Subject: [PATCH] Implement a BaseClass which support: - INotifyPropertyChanged - INotifyDataErrorInfo --- src/MahApps.Metro.Demo_v2/Core/BaseClass.cs | 80 +++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 src/MahApps.Metro.Demo_v2/Core/BaseClass.cs diff --git a/src/MahApps.Metro.Demo_v2/Core/BaseClass.cs b/src/MahApps.Metro.Demo_v2/Core/BaseClass.cs new file mode 100644 index 0000000000..e9e12cc77b --- /dev/null +++ b/src/MahApps.Metro.Demo_v2/Core/BaseClass.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MahApps.Demo.Core +{ + public class BaseClass : INotifyPropertyChanged, INotifyDataErrorInfo + { + #region INotifyPropertyChanged + + // This event tells the UI to update + public event PropertyChangedEventHandler PropertyChanged; + + public void RaisePropertyChanged(string PropertyName) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName)); + } + + #endregion INotifyPropertyChanged + + #region INotifyDataErrorInfo + + public event EventHandler ErrorsChanged; + + public bool HasErrors => _errorsByPropertyName.Count > 0; + + private readonly Dictionary> _errorsByPropertyName = new Dictionary>(); + + public IEnumerable GetErrors(string propertyName) + { + if (string.IsNullOrEmpty(propertyName)) + { + return null; + } + else + { + return _errorsByPropertyName.ContainsKey(propertyName) + ? _errorsByPropertyName[propertyName] + : null; + } + } + + public bool GetHasError(string PropertyName) + { + return _errorsByPropertyName.ContainsKey(PropertyName); + } + + public void AddError(string propertyName, string error) + { + if (!_errorsByPropertyName.ContainsKey(propertyName)) + _errorsByPropertyName[propertyName] = new List(); + + if (!_errorsByPropertyName[propertyName].Contains(error)) + { + _errorsByPropertyName[propertyName].Add(error); + OnErrorsChanged(propertyName); + } + } + + public void ClearErrors(string propertyName) + { + if (_errorsByPropertyName.ContainsKey(propertyName)) + { + _errorsByPropertyName.Remove(propertyName); + OnErrorsChanged(propertyName); + } + } + + public void OnErrorsChanged(string propertyName) + { + ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName)); + } + + #endregion INotifyDataErrorInfo + } +}