-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathBaseKVContainer.cs
95 lines (77 loc) · 2.81 KB
/
BaseKVContainer.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
84
85
86
87
88
89
90
91
92
93
94
95
namespace MapboxMaui;
public abstract class BaseKVContainer : INotifyCollectionChanged
{
protected BaseKVContainer()
{
properties = new Dictionary<string, object>();
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
public ReadOnlyDictionary<string, object> Properties => new(properties);
private readonly Dictionary<string, object> properties;
protected virtual BaseKVContainer SetProperty<T>(string name, T value, string group = null)
{
// Not allow to use empty string as a name
if (string.IsNullOrWhiteSpace(name)) return this;
name = name.Trim();
void SetOrRemoveProperty(Dictionary<string, object> container, string key, T value)
{
if (value == null)
{
if (!container.ContainsKey(key)) return;
CollectionChanged?.Invoke(
this,
new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Remove,
container.Single(x => x.Key == key)
)
);
container.Remove(name);
}
else
{
var action = container.ContainsKey(key)
? NotifyCollectionChangedAction.Replace
: NotifyCollectionChangedAction.Add;
container[name] = value;
CollectionChanged?.Invoke(
this,
new NotifyCollectionChangedEventArgs(
action,
container.Single(x => x.Key == key)
)
);
}
}
if (group == null ||
!properties.TryGetValue(group, out var groupValue) ||
groupValue is not Dictionary<string, object> groupProperties)
{
SetOrRemoveProperty(properties, name, value);
}
else
{
SetOrRemoveProperty(groupProperties, name, value);
}
return this;
}
protected virtual T GetProperty<T>(string name, T defaultValue, string group = null)
{
// Not allow to use empty string as a name
if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Invalid property name");
name = name.Trim();
if (group == null ||
!properties.TryGetValue(group, out var groupValue) ||
groupValue is not Dictionary<string, object> groupProperties)
{
if (properties.TryGetValue(name, out var value) && value is T result)
{
return result;
}
}
else if (groupProperties.TryGetValue(name, out var value) && value is T result)
{
return result;
}
return defaultValue;
}
}