-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathViewModelBase.cs
83 lines (73 loc) · 2.63 KB
/
ViewModelBase.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
namespace bagpipe {
class ViewModelBase : INotifyDataErrorInfo, INotifyPropertyChanged {
public bool HasErrors => knownErrors.Any();
public event PropertyChangedEventHandler PropertyChanged;
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
private readonly Dictionary<string, List<string>> knownErrors = new Dictionary<string, List<string>>();
protected void SetProperty<T>(ref T field, T value, [CallerMemberName]string property = null) {
if (property == null) {
throw new ArgumentNullException();
}
if (!EqualityComparer<T>.Default.Equals(field, value)) {
field = value;
InvokePropertyChanged(property);
}
}
protected void InvokePropertyChanged([CallerMemberName]string property = null) {
if (property == null) {
throw new ArgumentNullException();
}
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
public IEnumerable GetErrors(string property) {
if (property == null) {
throw new ArgumentNullException();
}
return knownErrors.GetValueOrDefault(property);
}
protected bool PropertyValid([CallerMemberName]string property = null) {
if (property == null) {
throw new ArgumentNullException();
}
return !(knownErrors.GetValueOrDefault(property)?.Any() ?? false);
}
protected void ClearErrors([CallerMemberName]string property = null) {
if (property == null) {
throw new ArgumentNullException();
}
knownErrors.Remove(property);
}
protected void ValidationCheck(bool isValid, string msg, [CallerMemberName]string property = null) {
if (property == null) {
throw new ArgumentNullException();
}
if (isValid) {
if (knownErrors.ContainsKey(property)) {
knownErrors[property].Remove(msg);
InvokeErrorsChanged(property);
}
} else {
if (!knownErrors.ContainsKey(property)) {
knownErrors[property] = new List<string>();
}
if (!knownErrors[property].Contains(msg)) {
knownErrors[property].Add(msg);
InvokeErrorsChanged(property);
}
}
}
protected void InvokeErrorsChanged([CallerMemberName]string property = null) {
if (property == null) {
throw new ArgumentNullException();
}
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(property));
InvokePropertyChanged(nameof(HasErrors));
}
}
}