From 5a1476375f58d3a115e6dcf52f1eff932570a983 Mon Sep 17 00:00:00 2001 From: Emmanuel Hansen Date: Fri, 1 Aug 2025 08:55:57 +0000 Subject: [PATCH] Set IsKeyboardFocusWithin to false when control is detached from visual tree (#19369) * add failing IsKeyboardFocusWithin test for popup * Set IsKeyboardWithin to false when detached from visual tree --- src/Avalonia.Base/Input/InputElement.cs | 2 + .../Primitives/PopupTests.cs | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/src/Avalonia.Base/Input/InputElement.cs b/src/Avalonia.Base/Input/InputElement.cs index 20f510efa6..8ce8e24c19 100644 --- a/src/Avalonia.Base/Input/InputElement.cs +++ b/src/Avalonia.Base/Input/InputElement.cs @@ -515,6 +515,8 @@ namespace Avalonia.Input { FocusManager.GetFocusManager(this)?.ClearFocusOnElementRemoved(this, e.Parent); } + + IsKeyboardFocusWithin = false; } /// diff --git a/tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs b/tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs index 86eb5f83a4..b3d250a4f2 100644 --- a/tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs +++ b/tests/Avalonia.Controls.UnitTests/Primitives/PopupTests.cs @@ -669,6 +669,51 @@ namespace Avalonia.Controls.UnitTests.Primitives } } + [Fact] + public void Popup_Should_Clear_Keyboard_Focus_From_Children_When_Closed() + { + using (CreateServicesWithFocus()) + { + var winButton = new Button(); + var window = PreparedWindow(new Panel { Children = { winButton }}); + + var border1 = new Border(); + var border2 = new Border(); + var button = new Button(); + border1.Child = border2; + border2.Child = button; + var popup = new Popup + { + PlacementTarget = window, + Child = new StackPanel + { + Children = + { + border1 + } + } + }; + + ((ISetLogicalParent)popup).SetParent(popup.PlacementTarget); + window.Show(); + winButton.Focus(); + popup.Open(); + + button.Focus(); + + var inputRoot = Assert.IsAssignableFrom(popup.Host); + + var focusManager = inputRoot.FocusManager!; + Assert.Same(button, focusManager.GetFocusedElement()); + + border1.Child = null; + + winButton.Focus(); + + Assert.False(border2.IsKeyboardFocusWithin); + } + } + [Fact] public void Closing_Popup_Sets_Focus_On_PlacementTarget() {