Переглянути джерело

fix: `SplitButton.Click` is not fired when `SplitButton` is not in focused (#16940)

* test: Check that `SplitButton.Click` is not fired when `SplitButton` is not in focused

* fix: `SplitButton.Click` is not fired when `SplitButton` is not in focused

* fix: Address review

* fix: Address review

---------

Co-authored-by: Julien Lebosquain <[email protected]>
workgroupengineering 1 рік тому
батько
коміт
b11574a122

+ 2 - 2
src/Avalonia.Controls/SplitButton/SplitButton.cs

@@ -346,7 +346,7 @@ namespace Avalonia.Controls
         {
             var key = e.Key;
 
-            if (key == Key.Space || key == Key.Enter)
+            if ((IsFocused && key == Key.Space) || key == Key.Enter)
             {
                 _isKeyboardPressed = true;
                 UpdatePseudoClasses();
@@ -360,7 +360,7 @@ namespace Avalonia.Controls
         {
             var key = e.Key;
 
-            if (key == Key.Space || key == Key.Enter)
+            if ((IsFocused && key == Key.Space) || key == Key.Enter)
             {
                 _isKeyboardPressed = false;
                 UpdatePseudoClasses();

+ 35 - 0
tests/Avalonia.Controls.UnitTests/SplitButtonTests.cs

@@ -1,6 +1,7 @@
 using System;
 using Avalonia.Controls.UnitTests.Utils;
 using Avalonia.Input;
+using Avalonia.Interactivity;
 using Avalonia.UnitTests;
 using Xunit;
 
@@ -30,4 +31,38 @@ public class SplitButtonTests : ScopedTestBase
 
         (target as IClickableControl).RaiseClick();
     }
+
+
+    [Fact]
+    void Should_Not_Fire_Click_Event_On_Space_Key_When_It_Is_Not_Focus()
+    {
+        using (UnitTestApplication.Start(TestServices.StyledWindow))
+        {
+            var raised = 0;
+            var target = new TextBox();
+            var button = new SplitButton()
+            {
+                Content = target,
+            };
+
+            var window = new Window { Content = button };
+            window.Show();
+
+            button.Click += (s, e) => ++raised;
+            target.Focus();
+            target.RaiseEvent(CreateKeyDownEvent(Key.Space));
+            target.RaiseEvent(CreateKeyUpEvent(Key.Space));
+            Assert.Equal(0, raised);
+        }
+    }
+
+    private static KeyEventArgs CreateKeyDownEvent(Key key, Interactive source = null)
+    {
+        return new KeyEventArgs { RoutedEvent = InputElement.KeyDownEvent, Key = key, Source = source };
+    }
+
+    private static KeyEventArgs CreateKeyUpEvent(Key key, Interactive source = null)
+    {
+        return new KeyEventArgs { RoutedEvent = InputElement.KeyUpEvent, Key = key, Source = source };
+    }
 }