RemoveClassAction.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using Avalonia.Controls;
  2. using Avalonia.Xaml.Interactivity;
  3. namespace Avalonia.Xaml.Interactions.Custom;
  4. /// <summary>
  5. /// Removes a specified <see cref="RemoveClassAction.ClassName"/> from <see cref="StyledElement.Classes"/> collection when invoked.
  6. /// </summary>
  7. public class RemoveClassAction : Avalonia.Xaml.Interactivity.Action
  8. {
  9. /// <summary>
  10. /// Identifies the <seealso cref="ClassName"/> avalonia property.
  11. /// </summary>
  12. public static readonly StyledProperty<string> ClassNameProperty =
  13. AvaloniaProperty.Register<RemoveClassAction, string>(nameof(ClassName));
  14. /// <summary>
  15. /// Identifies the <seealso cref="StyledElement"/> avalonia property.
  16. /// </summary>
  17. public static readonly StyledProperty<StyledElement?> StyledElementProperty =
  18. AvaloniaProperty.Register<RemoveClassAction, StyledElement?>(nameof(StyledElement));
  19. /// <summary>
  20. /// Gets or sets the class name that should be removed. This is a avalonia property.
  21. /// </summary>
  22. public string ClassName
  23. {
  24. get => GetValue(ClassNameProperty);
  25. set => SetValue(ClassNameProperty, value);
  26. }
  27. /// <summary>
  28. /// Gets or sets the target styled element that class name that should be removed from. This is a avalonia property.
  29. /// </summary>
  30. [ResolveByName]
  31. public StyledElement? StyledElement
  32. {
  33. get => GetValue(StyledElementProperty);
  34. set => SetValue(StyledElementProperty, value);
  35. }
  36. /// <summary>
  37. /// Executes the action.
  38. /// </summary>
  39. /// <param name="sender">The <see cref="object"/> that is passed to the action by the behavior. Generally this is <seealso cref="IBehavior.AssociatedObject"/> or a target object.</param>
  40. /// <param name="parameter">The value of this parameter is determined by the caller.</param>
  41. /// <returns>True if the class is successfully added; else false.</returns>
  42. public override object Execute(object? sender, object? parameter)
  43. {
  44. if (!IsEnabled)
  45. {
  46. return false;
  47. }
  48. var target = GetValue(StyledElementProperty) is not null ? StyledElement : sender as StyledElement;
  49. if (target is null || string.IsNullOrEmpty(ClassName))
  50. {
  51. return false;
  52. }
  53. if (target.Classes.Contains(ClassName))
  54. {
  55. target.Classes.Remove(ClassName);
  56. }
  57. return true;
  58. }
  59. }