using Avalonia.Controls; using Avalonia.Xaml.Interactivity; namespace Avalonia.Xaml.Interactions.Custom; /// /// Adds a specified to the collection when invoked. /// public class AddClassAction : Avalonia.Xaml.Interactivity.Action { /// /// Identifies the avalonia property. /// public static readonly StyledProperty ClassNameProperty = AvaloniaProperty.Register(nameof(ClassName)); /// /// Identifies the avalonia property. /// public static readonly StyledProperty StyledElementProperty = AvaloniaProperty.Register(nameof(StyledElement)); /// /// Identifies the avalonia property. /// public static readonly StyledProperty RemoveIfExistsProperty = AvaloniaProperty.Register(nameof(RemoveIfExists)); /// /// Gets or sets the class name that should be added. This is a avalonia property. /// public string ClassName { get => GetValue(ClassNameProperty); set => SetValue(ClassNameProperty, value); } /// /// Gets or sets the target styled element that class name that should be added to. This is a avalonia property. /// [ResolveByName] public StyledElement? StyledElement { get => GetValue(StyledElementProperty); set => SetValue(StyledElementProperty, value); } /// /// Gets or sets the flag indicated whether to remove the class if already exists before adding. This is a avalonia property. /// public bool RemoveIfExists { get => GetValue(RemoveIfExistsProperty); set => SetValue(RemoveIfExistsProperty, value); } /// /// Executes the action. /// /// The that is passed to the action by the behavior. Generally this is or a target object. /// The value of this parameter is determined by the caller. /// True if the class is successfully added; else false. public override object Execute(object? sender, object? parameter) { if (!IsEnabled) { return false; } var target = GetValue(StyledElementProperty) is not null ? StyledElement : sender as StyledElement; if (target is null || string.IsNullOrEmpty(ClassName)) { return false; } if (RemoveIfExists && target.Classes.Contains(ClassName)) { target.Classes.Remove(ClassName); } target.Classes.Add(ClassName); return true; } }