Created
November 26, 2020 14:33
-
-
Save SchreinerK/ac0a559c24cd853a3fc96bcf1f59d20b to your computer and use it in GitHub Desktop.
PropertyChangedDistributor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
namespace Common { | |
public sealed class PropertyChangedDistributor: IDisposable { | |
private readonly INotifyPropertyChanged _obj; | |
private readonly Dictionary<string, List<Entry>> _subscriptions = new Dictionary<string, List<Entry>>(); | |
public PropertyChangedDistributor(INotifyPropertyChanged obj) { | |
_obj = obj ?? throw new ArgumentNullException(nameof(obj)); | |
_obj.PropertyChanged += PropertyChanged; | |
} | |
private void PropertyChanged(object sender, PropertyChangedEventArgs e) { | |
if (!_subscriptions.TryGetValue(e.PropertyName, out var actions)) return; | |
foreach (var action in actions) { | |
if (action.Condition == null || action.Condition()) action.Action(); | |
} | |
} | |
public void Add(string propertyName, Action action) { | |
if (!_subscriptions.TryGetValue(propertyName, out var actions)) { | |
actions = new List<Entry> {new Entry(action)}; | |
_subscriptions.Add(propertyName, actions); | |
} else { | |
actions.Add(new Entry(action)); | |
} | |
} | |
public void Add(string propertyName, Func<bool> condition, Action action) { | |
if (!_subscriptions.TryGetValue(propertyName, out var actions)) { | |
actions = new List<Entry> {new Entry(condition, action)}; | |
_subscriptions.Add(propertyName, actions); | |
} else { | |
actions.Add(new Entry(condition, action)); | |
} | |
} | |
public void Dispose() { | |
_obj.PropertyChanged -= PropertyChanged; | |
_subscriptions.Clear(); | |
} | |
private class Entry { | |
public Entry(Action action) { | |
Action = action; | |
} | |
public Entry(Func<bool> condition, Action action) { | |
Condition = condition; | |
Action = action; | |
} | |
public Func<bool> Condition { get; set; } | |
public Action Action { get; set; } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment