Allow validation to be looked up by name

This commit is contained in:
TheXamlGuy
2024-09-27 19:55:45 +01:00
parent 0871c42438
commit bd577975b2
4 changed files with 70 additions and 3 deletions
@@ -0,0 +1,10 @@
namespace Toolkit.Foundation
{
public interface IReadOnlyIndexDictionary<TKey, TValue> :
IReadOnlyDictionary<TKey, TValue>
where TKey : notnull
{
KeyValuePair<TKey, TValue> this[int index] { get; }
}
}
+1 -1
View File
@@ -6,7 +6,7 @@ namespace Toolkit.Foundation;
public interface IValidation : public interface IValidation :
INotifyPropertyChanged INotifyPropertyChanged
{ {
IReadOnlyDictionary<string, string> Errors { get; } IReadOnlyIndexDictionary<string, string> Errors { get; }
bool HasErrors { get; } bool HasErrors { get; }
@@ -0,0 +1,56 @@
using System.Collections;
using System.Diagnostics.CodeAnalysis;
namespace Toolkit.Foundation;
public class ReadOnlyIndexDictionary<TKey, TValue> :
IReadOnlyDictionary<TKey, TValue>,
IReadOnlyIndexDictionary<TKey, TValue>
where TKey : notnull
{
private readonly Dictionary<TKey, TValue> dictionary;
private readonly List<KeyValuePair<TKey, TValue>> indexedItems;
public ReadOnlyIndexDictionary(IDictionary<TKey, TValue> items)
{
dictionary = new Dictionary<TKey, TValue>(items);
indexedItems = [.. dictionary];
}
public TValue this[TKey key] =>
dictionary[key];
public KeyValuePair<TKey, TValue> this[int index] =>
indexedItems[index];
public IEnumerable<TKey> Keys =>
dictionary.Keys;
public IEnumerable<TValue> Values =>
dictionary.Values;
public int Count => dictionary.Count;
public bool ContainsKey(TKey key) =>
dictionary.ContainsKey(key);
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() =>
dictionary.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => dictionary.GetEnumerator();
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
{
if (dictionary.TryGetValue(key, out TValue? localValue))
{
if (localValue is not null)
{
value = localValue;
return true;
}
}
value = default;
return false;
}
}
+3 -2
View File
@@ -10,8 +10,8 @@ public class Validation(IValidatorCollection validators) :
public event PropertyChangedEventHandler? PropertyChanged; public event PropertyChangedEventHandler? PropertyChanged;
public IReadOnlyDictionary<string, string> Errors => public IReadOnlyIndexDictionary<string, string> Errors =>
errors.AsReadOnly(); new ReadOnlyIndexDictionary<string, string>(errors);
public bool HasErrors => public bool HasErrors =>
Errors.Count > 0; Errors.Count > 0;
@@ -116,6 +116,7 @@ public class Validation(IValidatorCollection validators) :
OnPropertyChanged(nameof(Errors), null, null); OnPropertyChanged(nameof(Errors), null, null);
} }
} }
private string GetPropertyName<T>(Expression<Func<T>> expression) private string GetPropertyName<T>(Expression<Func<T>> expression)
{ {
return expression.Body switch return expression.Body switch