using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
///
/// A behavior that listens for a event on its source and executes its actions when that event is fired.
///
public class ButtonClickEventTriggerBehavior : StyledElementTrigger
{
private KeyModifiers _savedKeyModifiers = KeyModifiers.None;
///
/// Identifies the avalonia property.
///
public static readonly StyledProperty KeyModifiersProperty =
AvaloniaProperty.Register(nameof(KeyModifiers));
///
/// Gets or sets the required key modifiers to execute event handler. This is a avalonia property.
///
public KeyModifiers KeyModifiers
{
get => GetValue(KeyModifiersProperty);
set => SetValue(KeyModifiersProperty, value);
}
///
protected override void OnAttachedToVisualTree()
{
if (AssociatedObject is not null)
{
AssociatedObject.Click += AssociatedObject_OnClick;
AssociatedObject.AddHandler(InputElement.KeyDownEvent, Button_OnKeyDown, RoutingStrategies.Tunnel);
AssociatedObject.AddHandler(InputElement.KeyUpEvent, Button_OnKeyUp, RoutingStrategies.Tunnel);
}
}
///
protected override void OnDetachedFromVisualTree()
{
if (AssociatedObject is not null)
{
AssociatedObject.Click -= AssociatedObject_OnClick;
AssociatedObject.RemoveHandler(InputElement.KeyDownEvent, Button_OnKeyDown);
AssociatedObject.RemoveHandler(InputElement.KeyUpEvent, Button_OnKeyUp);
}
}
private void AssociatedObject_OnClick(object? sender, RoutedEventArgs e)
{
if (!IsEnabled)
{
return;
}
if (AssociatedObject is not null && KeyModifiers == _savedKeyModifiers)
{
Interaction.ExecuteActions(AssociatedObject, Actions, e);
}
}
private void Button_OnKeyDown(object? sender, KeyEventArgs e)
{
_savedKeyModifiers = e.KeyModifiers;
}
private void Button_OnKeyUp(object? sender, KeyEventArgs e)
{
_savedKeyModifiers = KeyModifiers.None;
}
}