简体   繁体   English

从组合框WPF中删除组合框项目

[英]Remove combobox item from combobox WPF

How to delete combobox item? 如何删除组合框项目? i tried this code but it does not work. 我尝试了此代码,但它不起作用。

  private void btnAdd_Click(object sender, RoutedEventArgs e)
    {
 foreach (var item in cbRooms.Items)
                {
                    if (((ComboBoxItem)item).Content.ToString() == cbRooms.Text.ToString())
                    {
                        cbRooms.Items.Remove(((ComboBoxItem)item).Content.ToString());
                    }
                }}

与其尝试删除字符串,不如尝试:

cbRooms.Items.Remove((ComboBoxItem)item))

Try removing the ComboBoxItem rather than: 尝试删除ComboBoxItem而不是:

(ComboBoxItem)item).Content.ToString()

Try: 尝试:

(item)

You may also need to refresh the combo box control after you remove the item: 删除项目后,您可能还需要刷新组合框控件:

cbRooms.Items.Refresh();

UPDATE UPDATE

You could try what kzen said in the comments of the OP. 您可以尝试kzen在OP的评论中说的话。 Use a List<ComboBoxItem> to store your items, and perform the add/remove operations on the List . 使用List<ComboBoxItem>存储您的项目,并在List上执行添加/删除操作。 Then bind the list to your ComboBox : 然后将列表绑定到您的ComboBox

cbRooms.ItemsSource = comboBoxItemList;

Then when you do your operations on the List call the refresh: 然后,当您在List上执行操作时,请调用刷新:

cbRooms.Items.Refresh();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM