Search code examples
c#comboboxmessagebox

Messagebox while using LostFocus event on editable comboBox


I face a problem while using LostFocus event for editable comboBox.

private void comboBox8_LostFocus(object sender, RoutedEventArgs e)
    {
        ...
            else if (8int <= 7int && 8int >= 100)
            {
                MessageBox.Show("Error description", "Error!", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            ...
    }

Everything works just fine except that messagebox show even if I click with mouse on comboBox text field for edit. There is no messagebox if I use "tab" from a previous field. But direct mouse click cause false messagebox. I need it only be shown when I use "tab" to leave that comboBox or click mouse somewhere else (lostfocus). Can anyone help me with an advice please? I can't find similar situation. Thank you.


Solution

  • You want to listen for the TextBox part of the ComboBox LostFocus instead.

            private void comboBox8_Loaded(object sender, RoutedEventArgs e)
            {
                TextBox tb = (TextBox)(sender as ComboBox).Template.FindName("PART_EditableTextBox", (sender as ComboBox));
                if (tb != null)
                    tb.LostFocus += new RoutedEventHandler(tb_LostFocus);
            }
    
            void tb_LostFocus(object sender, RoutedEventArgs e)
            {
                ...
                else if (8int <= 7int && 8int >= 100)
                {
                    MessageBox.Show("Error description", "Error!", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                ...
            }