【问题标题】:Editable Combobox are frozen to edit after selected可编辑的组合框在选择后被冻结以编辑
【发布时间】:2026-01-10 06:15:01
【问题描述】:

我在 wpf 控件中有可编辑的组合框。

<ComboBox Width="200"  Name="quickSearchText"
    TextBoxBase.TextChanged="searchTextChanged"
    IsTextSearchEnabled="False" 
    StaysOpenOnEdit="True" IsEditable="True">
</ComboBox>

在输入文本后,我正在更改组合框项目(如自动完成的文本框)。

private void searchTextChanged(object sender, TextChangedEventArgs e)
{
    string text = quickSearchText.Text; //Get typing text.
    List<string> autoList = new List<string>();

    autoList.AddRange(suggestions.Where(suggestion => !string.IsNullOrEmpty(text)&& suggestion.StartsWith(text))); //Get possible suggestions.

   // Show all, if text is empty.
   if (string.IsNullOrEmpty(text) && autoList.Count == 0)
   {
       autoList.AddRange(suggestions);
   }

   quickSearchText.ItemsSource = autoList;
   quickSearchText.IsDropDownOpen = autoList.Count != 0; //Open if any.
}

如果我从下拉列表中选择一个项目或输入文本并按Enter,TextboxBase 冻结并且我无法编辑它。 (但可以突出显示文本并打开/关闭下拉菜单)

如何解决?

【问题讨论】:

  • 您可以使用TextBox控制和Popup Control with Combobox。在 TextBox 的 TextChanged 事件中,您可以显示/隐藏 Popup
  • @Amol Bavannavar 谢谢。这是解决方案之一。但是为什么当前的解决方案不起作用?

标签: c# wpf


【解决方案1】:

由于这一行,当前的解决方案不起作用:

quickSearchText.ItemsSource = autoList;

这将重置您的 ComboBox 数据,因此对输入文本所做的所有更改都将丢失。

为了使您的解决方案正常工作,您应该使用 数据绑定,如下所示:

后面的代码:

public MainWindow()
{
    InitializeComponent();
    DataContext = this;
    autoList = new ObservableCollection<string>();
}

private List<string> suggestions;
public ObservableCollection<string> autoList { get; set; }
private void searchTextChanged(object sender, TextChangedEventArgs e)
{
    string text = quickSearchText.Text; //Get typing text.

    var suggestedList = suggestions.Where(suggestion => !string.IsNullOrEmpty(text) && suggestion.StartsWith(text)); //Get possible suggestions
    autoList.Clear();

    foreach (var item in suggestedList)
    {
        autoList.Add(item);
    }

    // Show all, if text is empty.
    if (string.IsNullOrEmpty(text) && autoList.Count == 0)
    {
        foreach (var item in suggestions)
        {
            autoList.Add(item);
        }
    }

    quickSearchText.IsDropDownOpen = autoList.Count != 0; //Open if any.
}

Xaml:

<ComboBox Width="200"  Name="quickSearchText"
            ItemsSource="{Binding autoList}"
            TextBoxBase.TextChanged="searchTextChanged"
            IsTextSearchEnabled="False" 
            StaysOpenOnEdit="True" IsEditable="True">
</ComboBox>

【讨论】:

  • 使用ObservableCollection对我有帮助,但是绑定的数据在View上没有更新,所以还是要通过代码重置ItemsSource。
【解决方案2】:

输入:

quickSearchText.ItemsSource = null;

作为 searchTextChanged 函数的第一行。似乎没有事先清除 ItemsSource 会导致奇怪的行为,将这一行放在首位似乎可以解决它。

【讨论】:

    【解决方案3】:

    将此添加到您的 searchTextChanged 方法中以再次启用编辑。

    quickSearchText.SelectedIndex = -1;
    

    【讨论】: