【问题标题】:Customize the drop box element selection of AutoCompleteBox in C# WPF自定义C# WPF中AutoCompleteBox的下拉框元素选择
【发布时间】:2023-03-06 22:05:02
【问题描述】:

我是 WPF 新手,现在我正试图弄清楚如何自定义 AutoCompleteBox。

我希望我的 AutoCompleteBox 能够输入多个由“;”分隔的文本元素。

例如,文本框可以有:

Apple; Banana; Cat

我已经自定义了我的过滤方法,它会在用户输入“;”后启用新的搜索。

但是烦人的是,如果我从下拉框中选择一个元素,原来的文本会被选中的元素替换。

比如文本框一开始有这个,下拉框里面有“香蕉”:

Apple; Ba

然后我在下拉框中选择“香蕉”,旧文本将被替换:

Banana

但我希望文本框是这样的:

Apple; Banana

有没有办法覆盖下拉框的选择事件,让它保留原来的文字?或者,有没有其他方法可以做到这一点?非常感谢!

【问题讨论】:

    标签: c# wpf visual-studio-2013 autocompletebox


    【解决方案1】:

    你可以使用 selectionchanged 事件,像这样:

     <Grid>
            <TextBox x:Name="txtInput" HorizontalAlignment="Left" Height="23" Margin="154,36,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="327"/>
            <ComboBox x:Name="comboBox" HorizontalAlignment="Left" SelectionChanged="comboBox_SelectionChanged" Margin="154,64,0,0" VerticalAlignment="Top" Width="120">
                <ComboBoxItem Content="Apple"/>
                <ComboBoxItem Content="Pear"/>
                <ComboBoxItem Content="Banana"/>
            </ComboBox>
    
        </Grid>
    
    
    
    private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                if(comboBox.SelectedIndex > -1)
                {
                    string tmp = txtInput.Text;
                    if (tmp.LastIndexOf(';') > 0)
                    {
                        txtInput.Text = tmp.Substring(0, tmp.LastIndexOf(';') + 1) + ((ComboBoxItem)comboBox.SelectedItem).Content;
                    }
                    else
                    {
                        txtInput.Text += ";" +((ComboBoxItem)comboBox.SelectedItem).Content;
                    }
    
                }
            }
    

    这只是一个例子,你应该分析你的字符串并做一些事情,再举一个例子:

    你输入Apple;Ba,在combobox中选择Banana,当然是把Ba换成Banana。但是如果你选择Pear,你确定把Ba换成Pear吗?您可以使用 string.StartWith 来决定是否替换它。

    【讨论】:

      【解决方案2】:

      如果您可以访问 Telerik 控制套件,则其中包含自动完整控制。它实现了开箱即用的所有功能。这是一个链接Telerik Auto Complete

      作为旁注,我不为 Telerik 工作,也没有从插入它们中得到任何东西。我真的很喜欢使用他们的产品!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-31
        • 1970-01-01
        • 2020-08-18
        • 2016-07-06
        • 2011-05-07
        • 2015-10-07
        相关资源
        最近更新 更多