ActionCollection.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Collections.Specialized;
  3. using Avalonia.Collections;
  4. namespace Avalonia.Xaml.Interactivity;
  5. /// <summary>
  6. /// Represents a collection of <see cref="IAction"/>'s.
  7. /// </summary>
  8. public class ActionCollection : AvaloniaList<AvaloniaObject>
  9. {
  10. /// <summary>
  11. /// Initializes a new instance of the <see cref="ActionCollection"/> class.
  12. /// </summary>
  13. public ActionCollection()
  14. {
  15. CollectionChanged += ActionCollection_CollectionChanged;
  16. }
  17. private void ActionCollection_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs eventArgs)
  18. {
  19. var collectionChangedAction = eventArgs.Action;
  20. switch (collectionChangedAction)
  21. {
  22. case NotifyCollectionChangedAction.Reset:
  23. {
  24. foreach (var item in this)
  25. {
  26. VerifyType(item);
  27. }
  28. break;
  29. }
  30. case NotifyCollectionChangedAction.Add or NotifyCollectionChangedAction.Replace:
  31. {
  32. var changedItem = eventArgs.NewItems?[0] as AvaloniaObject;
  33. VerifyType(changedItem);
  34. break;
  35. }
  36. }
  37. }
  38. private static void VerifyType(AvaloniaObject? item)
  39. {
  40. if (item is null)
  41. {
  42. return;
  43. }
  44. if (item is not IAction)
  45. {
  46. throw new InvalidOperationException(
  47. $"Only {nameof(IAction)} types are supported in an {nameof(ActionCollection)}.");
  48. }
  49. }
  50. }