首页 > 解决方案 > 如何根据输入的文本过滤和自动建议组合框项目?

问题描述

我按照以下链接创建了一个自定义组合框。我使用 c# 添加了一个组合框项目列表。

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

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

<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" />

如何做到这一点?

这可能与默认组合框。默认组合框自动建议以输入文本开头的项目,而不是检查该词是否包含在项目中。

创建自定义 ComboBox1 自定义 ComboBox2

标签: c#wpfcombobox

解决方案


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

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

推荐阅读