0

please have look on my code, this become an infinite loop while calling lostfocus event of combo box i need some data from database and user can select data only form list with typing options.

mainwindow.xaml

<Grid>
    <TextBox x:Name="txt1" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120" Margin="112,10,0,0"/>
    <ComboBox x:Name="cmb"  GotFocus="cmbgotfocus" LostKeyboardFocus="cmblost"  KeyDown="cmbkeydown" IsEditable="True"  HorizontalAlignment="Left" VerticalAlignment="Top" Width="238" Margin="112,50,0,0"  />
</Grid>

Class

    private void cmbkeydown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Return || e.Key == Key.Escape)
        {
            cmb.IsDropDownOpen = false;
        }
        else
        {
            cmb.IsDropDownOpen = true;
        }
    }

    private void cmblost(object sender, RoutedEventArgs e)
    {
        if (cmb.SelectedIndex < 0 && cmb.Text!="" )
        {
            MessageBox.Show("Please select a valid data from list only", "Warning");
            cmb.Focus();
         }
    }
J. Chomel
  • 8,193
  • 15
  • 41
  • 69

1 Answers1

0

If I got you correctly, you want user to type some text in the ComboBox, and if user's entry doesn't match any item, focus should remain on the TextBox present in the ComboBox.

<ComboBox x:Name="Cmb1" IsEditable="True" 
          Control.PreviewLostKeyboardFocus="Control_PreviewLostKeyboardFocus" ...> 

Handler code :

private void Control_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        if (!(e.OriginalSource is TextBox)) return;

        TextBox tb = (TextBox)e.OriginalSource;
        if (Cmb1.SelectedIndex < 0)
        {
            Cmb1.Text = "";
            e.Handled = true;
        }
    }

Please tell if this solves your issue.

AnjumSKhan
  • 9,647
  • 1
  • 26
  • 38