C# ComboBox GotFocus

后端 未结 3 1839
-上瘾入骨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:58

    You can solve this problem with next verification:

    private void myComboBox_GotFocus(object sender, RoutedEventArgs e)
    {
        if (e.OriginalSource.GetType() == typeof(ComboBoxItem))
            return;
        //Your code here
    }
    

    This code will filter all focus events from items (because they use bubble routing event). But there is another problem - specific behaviour of WPF ComboBox focus: when you open drop-down list with items your ComboBox losing focus and items get. When you select some item - item losing focus and ComboBox get back. Drop-down list is like another control. You can see this by simple code:

    private void myComboBox_GotFocus(object sender, RoutedEventArgs e)
    {
        if (e.OriginalSource.GetType() != typeof(ComboBoxItem))
        {
            Trace.WriteLine("Got " + DateTime.Now);
        }
    }
    
    private void myComboBox_LostFocus(object sender, RoutedEventArgs e)
    {
        if (e.OriginalSource.GetType() != typeof(ComboBoxItem))
        {
            Trace.WriteLine("Lost " + DateTime.Now);
        }
    }
    

    So you will get anyway atleast two focus events: when you select ComboBox and when you selecting something in it (focus will return to ComboBox).

    To filter returned focus after selecting item, you can try to use DropDownOpened/DropDownClosed events with some field-flag.

    So the final code with only 1 event of getting focus:

    private bool returnedFocus = false;
    
    private void myComboBox_GotFocus(object sender, RoutedEventArgs e)
    {
        if (e.OriginalSource.GetType() != typeof(ComboBoxItem) && !returnedFocus)
        {
            //Your code.
        }
    }
    
    private void myComboBox_LostFocus(object sender, RoutedEventArgs e)
    {
        if (e.OriginalSource.GetType() != typeof(ComboBoxItem))
        {
            ComboBox cb = (ComboBox)sender;
            returnedFocus = cb.IsDropDownOpen;
        }
    }
    

    Choose from this examples what you actually need more for your application.

提交回复
热议问题