在被过滤的组合箱子的箭头键

时间:2016-01-05 14:52:25

标签: c# wpf filter combobox

我有一个简单的组合框,其中有一个数据表,使用.DefaultView作为项目源。我在组合框上放置了一个过滤器,其中包含以下代码:

    private void FilterCombobox(ComboBox cmb, string columnName)
    {
        DataView view = (DataView)cmb.ItemsSource;
        view.RowFilter = (columnName + " like '*" + cmb.Text + "*'");

        cmb.ItemsSource = view;
        cmb.IsDropDownOpen = true;
    }

组合框的XAML是:

<ComboBox x:Name="cmbRigNum" KeyboardNavigation.TabIndex="3" HorizontalAlignment="Left" Margin="470,440,0,0" VerticalAlignment="Top" Width="206" SelectionChanged="cmbRigNum_SelectionChanged" IsEditable="True" StaysOpenOnEdit="True" IsTextSearchEnabled="False" FontFamily="Arial" FontSize="14" KeyUp="cmbRigNum_KeyUp"/>     

更新:Key_Up事件:

    private void cmbRigNum_KeyUp(object sender, KeyEventArgs e)
    {
        FilterCombobox(cmbRigNum, "RigNumber");         
    }

当用户键入时,一切都运行得很好,但只要使用箭头键进行选择,过滤后的列表就会消失,并且组合框中的值将被清除。如何启用用户使用箭头键导航到用户最初键入时显示的已过滤列表?

2 个答案:

答案 0 :(得分:1)

我怀疑它是你的“cmbRigNum_KeyUp”方法中的东西。

编辑: 因此,如果您不希望它使用箭头键更改过滤器,您可以这样做吗?

private void cmbRigNum_KeyUp(object sender, KeyEventArgs e)
{
    if (char.IsLetter(e.Keychar) || char.IsDigit(e.KeyChar)) // Add more characters as needed.
    {
        FilterCombobox(cmbRigNum, "RigNumber");
    {
}

答案 1 :(得分:1)

在玩了@Topher Birth给出的建议之后,我找到了问题的解决方案。对于在这里遇到同样问题的人来说,解决问题的代码是:

     private void FilterCombobox(ComboBox cmb, string columnName)
    {
        //because the itemsSource of the comboboxes are datatables, filtering is not supported. Converting the itemsSource to a
        //dataview will allow the functionality of filtering to be implemented
        DataView view = (DataView)cmb.ItemsSource;
        view.RowFilter = (columnName + " like '*" + cmb.Text + "*'");

        cmb.ItemsSource = view;
        cmb.IsDropDownOpen = true;
    }

    private void cmbRigNum_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key != Key.Down & e.Key != Key.Up) 
        {
            e.Handled = true;
            FilterCombobox(cmbRigNum, "RigNumber");
        }
    }

无法相信它实际上是如此简单。感谢所有的投入!