C# ComboBox GotFocus

c#, combobox, focus, wpf

Solution

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.

Problem

I have a C# `ComboBox` using WPF. I have code that executes when the `ComboBox`'s `GotFocus` is activated. The issue is that the `GotFocus` event is executed every time a selection is made from the `ComboBox`. For example, the `GotFocus` is executed when you first click on the `ComboBox` and then when you make a selection even though you have not click on any other control. Is it possible to prevent this event from firing if a selection is being made in the list or is there a flag or something else in the event handler that can be used to determine if the `GotFocus` event handler was fired as a result of the user selecting an item in the list?

Original source