如何根据输入的文本过滤并自动建议组合框项目?

时间:2019-05-10 05:34:35

标签: c# wpf combobox

我已经跟随以下链接创建了一个自定义组合框。我已经使用c#添加了组合框项目的列表。

如果我在自定义组合框中键入文本,则不会根据搜索文本过滤项目是否包含单词。

自定义组合框仅列出其中的所有项目。 我希望我的组合框的行为就像输入word一样,它应该过滤结果并在组合框搜索中自动建议。

<local:FilteredComboBox x:Name="FilteredCmb"  IsEditable="True"
            IsTextSearchEnabled="True" 
            Padding="4 3" 
            MinWidth="200" Grid.ColumnSpan="6" 
            Grid.Column="2" Margin="0,77,0,49" Grid.Row="1" />

如何实现?

使用默认组合框是否可以做到这一点。 默认的组合框会自动建议以输入的文本开头的项目,而不是检查项目中是否包含单词。

Create Custom ComboBox1 Custom ComboBox2

1 个答案:

答案 0 :(得分:0)

我已经使用组合框启动事件来过滤结果。

<local:FilteredComboBox x:Name="FilteredCmb"  IsEditable="True" 
IsTextSearchEnabled="False" **KeyUp="FilteredCmb_KeyUp"** Padding="4 3" MinWidth="200" 
Grid.ColumnSpan="6" Grid.Column="2" Margin="0,77,0,49" Grid.Row="1" />

C#代码

private void FilteredCmb_KeyUp(object sender, KeyEventArgs e)
{
    List<BoxItem> filteredItems = new List<BoxItem>();

    for (int i = 0; i < cmbItems.Count; i++)
    {
        string currentItem = cmbItems[i].Text.ToLower();

        // get the text in the editable combo box 
        string typedText = FilteredCmb.Text.ToLower();

        if (currentItem.Contains(typedText))
        {
            filteredItems.Add(cmbItems[i]);
        }

    }

// Clear the combo box before adding new items to Combo Box

    foreach(BoxItem item in filteredItems)
    {
        FilteredCmb.Items.Add(item);
    }

    FilteredCmb.IsDropDownOpen = true;
}