From 218ec6bfdbc782a1841590deddc8cb49fdf15fb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wies=C5=82aw=20S=CC=8Colte=CC=81s?= Date: Wed, 24 Apr 2024 12:43:47 +0200 Subject: [PATCH] Add ExecuteCommandOnLostFocusBehavior --- .../ExecuteCommandOnLostFocusBehavior.cs | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/Avalonia.Xaml.Interactions.Custom/ExecuteCommandOnLostFocusBehavior.cs diff --git a/src/Avalonia.Xaml.Interactions.Custom/ExecuteCommandOnLostFocusBehavior.cs b/src/Avalonia.Xaml.Interactions.Custom/ExecuteCommandOnLostFocusBehavior.cs new file mode 100644 index 00000000..439d21de --- /dev/null +++ b/src/Avalonia.Xaml.Interactions.Custom/ExecuteCommandOnLostFocusBehavior.cs @@ -0,0 +1,42 @@ +using System.Reactive.Disposables; +using Avalonia.Input; +using Avalonia.Interactivity; + +namespace Avalonia.Xaml.Interactions.Custom; + +/// +/// +/// +public class ExecuteCommandOnLostFocusBehavior : ExecuteCommandBehaviorBase +{ + /// + /// + /// + /// + protected override void OnAttachedToVisualTree(CompositeDisposable disposable) + { + var dispose = AssociatedObject? + .AddDisposableHandler( + InputElement.LostFocusEvent, + AssociatedObject_LostFocus, + RoutingStrategies.Tunnel | RoutingStrategies.Bubble); + + if (dispose is not null) + { + disposable.Add(dispose); + } + } + + private void AssociatedObject_LostFocus(object? sender, RoutedEventArgs e) + { + if (e.Handled) + { + return; + } + + if (ExecuteCommand()) + { + e.Handled = true; + } + } +}