using System.Reactive.Disposables;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
///
/// A behavior that allows to show control on key down event.
///
public class ShowOnKeyDownBehavior : ShowBehaviorBase
{
///
/// Identifies the avalonia property.
///
public static readonly StyledProperty KeyProperty =
AvaloniaProperty.Register(nameof(Key));
///
///
///
public static readonly StyledProperty GestureProperty =
AvaloniaProperty.Register(nameof(Gesture));
///
/// Gets or sets the key. This is a avalonia property.
///
public Key? Key
{
get => GetValue(KeyProperty);
set => SetValue(KeyProperty, value);
}
///
///
///
public KeyGesture? Gesture
{
get => GetValue(GestureProperty);
set => SetValue(GestureProperty, value);
}
///
///
///
///
protected override void OnAttachedToVisualTree(CompositeDisposable disposable)
{
var dispose = AssociatedObject?
.AddDisposableHandler(
InputElement.KeyDownEvent,
AssociatedObject_KeyDown,
EventRoutingStrategy);
if (dispose is not null)
{
disposable.Add(dispose);
}
}
private void AssociatedObject_KeyDown(object? sender, KeyEventArgs e)
{
var haveKey = Key is not null && e.Key == Key;
var haveGesture = Gesture is not null && Gesture.Matches(e);
if (!haveKey && !haveGesture)
{
return;
}
Show();
}
}