WPF Combobox lostfocus事件成为无限lopp

时间:2016-09-23 12:36:23

标签: wpf combobox

请查看我的代码, 这会在调用组合框的lostfocus事件时变成无限循环 我需要来自数据库的一些数据,用户可以选择仅带有打字选项的数据表单。

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>

    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();
         }
    }

1 个答案:

答案 0 :(得分:0)

如果我找到了你,你希望用户在ComboBox中输入一些文字,如果用户的条目与任何项目都不匹配,则焦点应保留在{{1} }出现在TextBox

ComboBox

处理程序代码:

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

请告知这是否解决了您的问题。