comparison SilverlightGlimpse/SilverlightValidation/ViewModels/ViewModelBase.cs @ 69:a0bcd783e612

Latest work
author Steven Hollidge <stevenhollidge@hotmail.com>
date Mon, 23 Apr 2012 11:06:10 +0100
parents
children 96e6fbd70f49
comparison
equal deleted inserted replaced
68:81337ebf885a 69:a0bcd783e612
1 using System;
2 using System.Collections;
3 using System.ComponentModel;
4 using System.Linq;
5
6 namespace SilverlightValidation.ViewModels
7 {
8 public class ViewModelBase : INotifyPropertyChanged, INotifyDataErrorInfo
9 {
10 #region INotifyPropertyChanged method plus event
11
12 public event PropertyChangedEventHandler PropertyChanged = delegate { };
13
14 protected void RaisePropertyChanged(string propertyName)
15 {
16 PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
17 }
18
19 #endregion
20
21 #region INotifyDataErrorInfo methods and helpers
22
23 private readonly Dictionary<string, List<string>> _errors = new Dictionary<string, List<string>>();
24
25 public void SetError(string propertyName, string errorMessage)
26 {
27 if (!_errors.ContainsKey(propertyName))
28 _errors.Add(propertyName, new List<string> { errorMessage });
29
30 RaiseErrorsChanged(propertyName);
31 }
32
33 protected void ClearError(string propertyName)
34 {
35 if (_errors.ContainsKey(propertyName))
36 {
37 _errors.Remove(propertyName);
38 RaiseErrorsChanged(propertyName);
39 }
40 }
41
42 protected void ClearAllErrors()
43 {
44 var errors = _errors.Select(error => error.Key).ToList();
45
46 foreach (var propertyName in errors)
47 ClearError(propertyName);
48 }
49
50 public void RaiseErrorsChanged(string propertyName)
51 {
52 ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
53 }
54
55 public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged = delegate { };
56
57 public IEnumerable GetErrors(string propertyName)
58 {
59 if (propertyName == null) return null;
60 return _errors.ContainsKey(propertyName)
61 ? _errors[propertyName]
62 : null;
63 }
64
65 public bool HasErrors
66 {
67 get { return _errors.Count > 0; }
68 }
69
70 #endregion
71 }
72 }