C# ComboBox GotFocus

后端 未结 3 1845
-上瘾入骨i
-上瘾入骨i 2021-02-05 17:21

I have a C# ComboBox using WPF. I have code that executes when the ComboBox\'s GotFocus is activated. The issue is that the GotFoc

3条回答
  •  心在旅途
    2021-02-05 17:40

    Another solution is used is to determine whether the new focused element is an existing item in the combobox. If true then the LostFocus event should not be performed, because the combobox still has focus. Otherwise an element outside the combobox received focus.

    In the code snipplet below I added the functionality in a custom combobox class

    public class MyComboBox : System.Windows.Controls.Combobox
    {
        protected override void OnLostFocus(RoutedEventArgs e)
        {
            //Get the new focused element and in case this is not an existing item of the current combobox then perform a lost focus command.
            //Otherwise the drop down items have been opened and is still focused on the current combobox
            var focusedElement = FocusManager.GetFocusedElement(FocusManager.GetFocusScope(this));
            if (!(focusedElement is ComboBoxItem && ItemsControl.ItemsControlFromItemContainer(focusedElement as ComboBoxItem) == this))
            {
                base.OnLostFocus(e);
                /* Your code here... */
            }
        }
    }
    

提交回复
热议问题