【问题标题】:Combobox Autocomplete: How to set a custom "match mode" [duplicate]组合框自动完成:如何设置自定义“匹配模式”[重复]
【发布时间】:2012-05-04 03:04:25
【问题描述】:

可能重复:
C# AutoComplete

我有一个标准的 winform 组合框。我已将其 AutoComplete 属性设置为 true。我想更改由 UI 自动完成的键入文本和项目文本之间的比较。

类似:

autoCompleteCombo.XXXX = new Func<string, string, bool> { (search, item) => item.Contains(search) };

注意:所写的函数只是一个例子。我真正想要的更复杂一点。

【问题讨论】:

    标签: .net winforms autocomplete combobox


    【解决方案1】:

    由于您更新了您的问题,我更了解您的问题。您还说基础数据和功能不相关,这使得您很难准确理解您要实现的目标,因此我的建议是创建一个自定义 ComboBox 并查看您是否可以处理匹配靠自己。


    我认为编写一个函数来测试输入的文本是否是ComboBox 中的项目的最优雅的方法是使用扩展方法。您的电话将如下所示:
    // see if the Text typed in the combobox is in the autocomplete list
    bool bFoundAuto = autoCompleteCombo.TextIsAutocompleteItem();
    
    // see if the Text type in the combobox is an item in the items list
    bool bFoundItem = autoCompleteCombo.TextIsItem();
    

    可以按如下方式创建扩展方法,您可以在其中准确自定义搜索逻辑的工作方式。在我下面写的两个扩展方法中,它们只是检查输入到ComboBox 中的文本是否在AutoCompleteCustomSource 集合中找到,或者在第二个函数中,是否在Items 集合中找到文本.

    public static class MyExtensions
    {
        // returns true if the Text property value is found in the 
        // AutoCompleteCustomSource collection
        public static bool TextIsAutocompleteItem(this ComboBox cb)
        {
            return cb.AutoCompleteCustomSource.OfType<string>()
                .Where(a => a.ToLower() == cb.Text.ToLower()).Any();
        }
    
        // returns true of the Text property value is found in the Items col
        public static bool TextIsItem(this ComboBox cb)
        {
            return cb.Items.OfType<string>()
                .Where(a => a.ToLower() == cb.Text.ToLower()).Any();
        }
    }   
    

    【讨论】:

    • 我会在哪里使用它?你能再指导我一点吗?第二个代码是方法。好了,第一个代码我应该写在哪里?
    • 您可以将MyExtensions 类放在您的项目@Diego 中它自己的文件中。只需将其保存在与表单相同的命名空间中即可。然后,在代码中您需要检查输入的文本是否是您调用autoCompleteCombo.TextIsItem(); 的组合框中的项目。
    • 我认为我们有一个误解。我想要做的是拥有 AutoComplete 的所有功能,但是当它(来自 ComboBox 的代码)搜索匹配的项目时,它使用自定义比较器。
    • @Diego,您将不得不编辑您的原始问题,并包括您将组合框项目和/或自动完成绑定到的类,以及您期望键入的文本应该如何的描述与基础项目相匹配。
    • 我已经编辑了我的问题以避免误解。我认为这已经足够清楚了。我不认为组合框项目的类型或定义匹配的函数在这里是相关的。
    猜你喜欢
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 2014-11-15
    相关资源
    最近更新 更多