wpf 使用下拉菜单创建自动完成文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36303629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:44:04  来源:igfitidea点击:

Creating an autocomplete textbox with dropdown

wpfautocompletebox

提问by maran

My Problem:

我的问题:

I have a list of 118 chemical element names. And I wish to make a textbox in which as I type it will throw a dropdown menu with suggestion of names. I made this textbox in winforms and it was piece of cake however my efforts of making it in wpf are in vain. I've tried extended wpf toolkit, nimgoble and some other autocomplete textbox libs. So far dead end...I'm also new to wpf so maybe I'm missing something with these libs? I can't make them list my items and some won't even show the dropdown menu.

我有一个包含 118 个化学元素名称的列表。我希望制作一个文本框,当我在其中输入时,它会抛出一个带有名称建议的下拉菜单。我在 winforms 中制作了这个文本框,这是小菜一碟,但是我在 wpf 中制作它的努力是徒劳的。我尝试过扩展 wpf 工具包、nimgoble 和其他一些自动完成文本框库。到目前为止的死胡同......我也是 wpf 的新手,所以也许我错过了这些库的一些东西?我不能让他们列出我的项目,有些甚至不会显示下拉菜单。

Heres what I wanted:

这是我想要的:

enter image description here

在此处输入图片说明

Here's how I finally achieved it:

这是我最终实现它的方式:

So I solved this by using a combination of textbox and listbox. Where in textbox user types and as it changes (textbox changed event) it's checking for matches inside a list that holds names of all 118 elements and displays matches for the text typed in, inside listbox. Here's the code:

所以我通过使用文本框和列表框的组合解决了这个问题。在文本框中用户键入的位置和更改时(文本框更改事件),它正在检查包含所有 118 个元素的名称的列表中的匹配项,并显示在列表框中键入的文本的匹配项。这是代码:

private void textBox_TextChanged(object sender, TextChangedEventArgs e)
    {

        listBox.Items.Clear();


        if (textBox.Text.Trim() != "")
        {
            string regexPattern = (textBox.Text.ToString()) + "\w*";
            regexPattern = char.ToUpper(regexPattern[0]) + regexPattern.Substring(1); //prvo slovo veliko

            Match match = Regex.Match(ElementNames.allElements, regexPattern);
            while (match.Success && match.Value != "")
            {
                listBox.Items.Add(match.Value.ToString());
                listBox.Visibility = Visibility.Visible;

                match = match.NextMatch();
            }
        }

            if (listBox.Items.IsEmpty || listBox.Items.Count == 119)
            {
                listBox.Visibility = Visibility.Collapsed;
                if (listBox.Items.Count == 119) listBox.Items.Clear();
            }

        HighlightElementsOnTable();
        OtherButtonsHighlight();
        BringBackColors();
    }

回答by H.B.

You can use a ComboBoxwith IsEditable=true.

您可以使用ComboBoxwith IsEditable=true