From c0f2c33c59a4454b57e0e1caf9f4596c97cc8dbc Mon Sep 17 00:00:00 2001 From: pavelovcharov <1357165+pavelovcharov@users.noreply.github.com> Date: Fri, 21 Mar 2025 14:59:07 +0300 Subject: [PATCH] Button.IsDefault should not work when button is not effectively visible (#18484) --- src/Avalonia.Controls/Button.cs | 4 +- .../ButtonTests.cs | 42 +++++++++++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/src/Avalonia.Controls/Button.cs b/src/Avalonia.Controls/Button.cs index 614847ee4e..88710cb5ff 100644 --- a/src/Avalonia.Controls/Button.cs +++ b/src/Avalonia.Controls/Button.cs @@ -659,7 +659,7 @@ namespace Avalonia.Controls /// The event args. private void RootDefaultKeyDown(object? sender, KeyEventArgs e) { - if (e.Key == Key.Enter && IsVisible && IsEnabled) + if (e.Key == Key.Enter && IsEffectivelyVisible && IsEffectivelyEnabled) { OnClick(); e.Handled = true; @@ -673,7 +673,7 @@ namespace Avalonia.Controls /// The event args. private void RootCancelKeyDown(object? sender, KeyEventArgs e) { - if (e.Key == Key.Escape && IsVisible && IsEnabled) + if (e.Key == Key.Escape && IsEffectivelyVisible && IsEffectivelyEnabled) { OnClick(); e.Handled = true; diff --git a/tests/Avalonia.Controls.UnitTests/ButtonTests.cs b/tests/Avalonia.Controls.UnitTests/ButtonTests.cs index e3b974491a..c16f68ef96 100644 --- a/tests/Avalonia.Controls.UnitTests/ButtonTests.cs +++ b/tests/Avalonia.Controls.UnitTests/ButtonTests.cs @@ -448,6 +448,27 @@ namespace Avalonia.Controls.UnitTests Assert.Equal(2, raised); } } + + [Fact] + public void Button_IsDefault_Should_Not_Work_When_Button_Is_Not_Effectively_Visible() + { + using (UnitTestApplication.Start(TestServices.StyledWindow)) + { + var raised = 0; + var panel = new Panel(); + var target = new Button(); + panel.Children.Add(target); + var window = new Window { Content = panel }; + window.Show(); + + target.Click += (s, e) => ++raised; + + target.IsDefault = true; + panel.IsVisible = false; + window.RaiseEvent(CreateKeyDownEvent(Key.Enter)); + Assert.Equal(0, raised); + } + } [Fact] public void Button_IsCancel_Works() @@ -482,6 +503,27 @@ namespace Avalonia.Controls.UnitTests Assert.Equal(2, raised); } } + + [Fact] + public void Button_IsCancel_Should_Not_Work_When_Button_Is_Not_Effectively_Visible() + { + using (UnitTestApplication.Start(TestServices.StyledWindow)) + { + var raised = 0; + var panel = new Panel(); + var target = new Button(); + panel.Children.Add(target); + var window = new Window { Content = panel }; + window.Show(); + + target.Click += (s, e) => ++raised; + + target.IsCancel = true; + panel.IsVisible = false; + window.RaiseEvent(CreateKeyDownEvent(Key.Escape)); + Assert.Equal(0, raised); + } + } [Fact] public void Button_CommandParameter_Does_Not_Change_While_Execution()