using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
///
/// A behavior that allows to hide control on key down event.
///
public class HideOnKeyPressedBehavior : StyledElementBehavior
{
///
/// Identifies the avalonia property.
///
public static readonly StyledProperty TargetControlProperty =
AvaloniaProperty.Register(nameof(TargetControl));
///
/// Identifies the avalonia property.
///
public static readonly StyledProperty KeyProperty =
AvaloniaProperty.Register(nameof(Key), Key.Escape);
///
/// Gets or sets the target control. This is a avalonia property.
///
[ResolveByName]
public Control? TargetControl
{
get => GetValue(TargetControlProperty);
set => SetValue(TargetControlProperty, value);
}
///
/// Gets or sets the key. This is a avalonia property.
///
public Key Key
{
get => GetValue(KeyProperty);
set => SetValue(KeyProperty, value);
}
///
protected override void OnAttachedToVisualTree()
{
AssociatedObject?.AddHandler(InputElement.KeyDownEvent, AssociatedObject_KeyDown,
RoutingStrategies.Tunnel | RoutingStrategies.Bubble);
}
///
protected override void OnDetachedFromVisualTree()
{
AssociatedObject?.RemoveHandler(InputElement.KeyDownEvent, AssociatedObject_KeyDown);
}
private void AssociatedObject_KeyDown(object? sender, KeyEventArgs e)
{
if (e.Key == Key && TargetControl is not null)
{
TargetControl.IsVisible = false;
}
}
}