From afc7a07d285e08d905c58dd5978441c155b2f296 Mon Sep 17 00:00:00 2001 From: Roy Ben-Shabat Date: Tue, 19 Dec 2017 10:25:40 +0200 Subject: MERGE. --- Software/Visual_Studio/Tango.SharedUI/ViewModel.cs | 57 ++++++++++++++++++++-- 1 file changed, 54 insertions(+), 3 deletions(-) (limited to 'Software/Visual_Studio/Tango.SharedUI/ViewModel.cs') diff --git a/Software/Visual_Studio/Tango.SharedUI/ViewModel.cs b/Software/Visual_Studio/Tango.SharedUI/ViewModel.cs index 281a6c03d..0dac0ce48 100644 --- a/Software/Visual_Studio/Tango.SharedUI/ViewModel.cs +++ b/Software/Visual_Studio/Tango.SharedUI/ViewModel.cs @@ -1,6 +1,10 @@ using System; +using System.Collections; using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; using System.Linq; +using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -8,9 +12,56 @@ using Tango.Core; namespace Tango.SharedUI { - public abstract class ViewModel : ExtendedObject + public abstract class ViewModel : ExtendedObject, INotifyDataErrorInfo { + private List> _currentErrors = new List>(); + private bool _hasErrors; + public bool HasErrors + { + get { return _hasErrors; } + set { _hasErrors = value; RaisePropertyChangedAuto(); } + } + + public event EventHandler ErrorsChanged; + + public virtual IEnumerable GetErrors(string propertyName) + { + return _currentErrors.Where(x => x.Key == propertyName).Select(x => x.Value).ToList(); + } + + protected void RaiseError(String propName) + { + ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propName)); + } + + protected bool Validate() + { + OnValidating(); + + HasErrors = false; + _currentErrors.Clear(); + + foreach (var prop in this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + foreach (var validation in prop.GetCustomAttributes()) + { + if (!validation.IsValid(prop.GetValue(this))) + { + HasErrors = true; + _currentErrors.Add(new KeyValuePair(prop.Name, validation.ErrorMessage)); + RaiseError(prop.Name); + } + } + } + + return !HasErrors; + } + + protected virtual void OnValidating() + { + + } } public abstract class ViewModel : ViewModel where T : IView @@ -29,13 +80,13 @@ namespace Tango.SharedUI public ViewModel(T view, bool delayed) { - Task.Factory.StartNew(() => + Task.Factory.StartNew(() => { while (view == null) { Thread.Sleep(10); } - }).ContinueWith((c) => + }).ContinueWith((c) => { View = view; View.ViewAttached += (x, e) => -- cgit v1.3.1