PropertyWatcherBase.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright © 2023 Steffen Cole Blake
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining
  4. // a copy of this software and associated documentation files (the “Software”),
  5. // to deal in the Software without restriction, including without limitation
  6. // the rights to use, copy, modify, merge, publish, distribute, sublicense,
  7. // and/or sell copies of the Software, and to permit persons to whom the Software
  8. // is furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in all
  11. // copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  14. // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  15. // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  16. // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  17. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  18. // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  19. //
  20. using System.ComponentModel;
  21. using System.Runtime.CompilerServices;
  22. public abstract class PropertyWatcherBase : INotifyPropertyChanged
  23. {
  24. public event PropertyChangedEventHandler PropertyChanged;
  25. protected void Mutate<T>(ref T target, T value, [CallerMemberName] string name = null)
  26. {
  27. if (target.Equals(value))
  28. return;
  29. target = value;
  30. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
  31. }
  32. protected void BindChild<T>(ref T target, T value, [CallerMemberName] string name = null)
  33. where T : INotifyPropertyChanged
  34. {
  35. target = value;
  36. target.PropertyChanged += (sender, e) =>
  37. {
  38. PropertyChanged?.Invoke(sender, new PropertyChangedEventArgs($"{name}.{e.PropertyName}"));
  39. PropertyChanged?.Invoke(sender, new PropertyChangedEventArgs($"{name}"));
  40. };
  41. }
  42. }