Browse Source

focus dropdown item in more safe manner

Andrey Kunchev 7 years ago
parent
commit
d26d984256
1 changed files with 16 additions and 7 deletions
  1. 16 7
      src/Avalonia.Controls/DropDown.cs

+ 16 - 7
src/Avalonia.Controls/DropDown.cs

@@ -170,6 +170,7 @@ namespace Avalonia.Controls
                     e.Handled = true;
                 }
             }
+
             base.OnPointerPressed(e);
         }
 
@@ -199,18 +200,26 @@ namespace Avalonia.Controls
 
         private void PopupOpened(object sender, EventArgs e)
         {
-            var selectedIndex = SelectedIndex;
-
-            if (selectedIndex != -1)
-            {
-                var container = ItemContainerGenerator.ContainerFromIndex(selectedIndex);
-                container?.Focus();
-            }
+            TryFocusSelectedItem();
         }
 
         private void SelectedItemChanged(AvaloniaPropertyChangedEventArgs e)
         {
             UpdateSelectionBoxItem(e.NewValue);
+            TryFocusSelectedItem();
+        }
+
+        private void TryFocusSelectedItem()
+        {
+            var selectedIndex = SelectedIndex;
+            if (IsDropDownOpen && selectedIndex != -1)
+            {
+                var container = ItemContainerGenerator.ContainerFromIndex(selectedIndex);
+                if (container != null && container.Focusable)
+                {
+                    container.Focus();
+                }
+            }
         }
 
         private void UpdateSelectionBoxItem(object item)