C# 检查组合框是否包含项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18163036/
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-08-10 11:26:16  来源:igfitidea点击:

Check if a ComboBox Contains Item

c#.netwpfxamlcombobox

提问by Elmo

I have this:

我有这个:

<ComboBox SelectedValuePath="Content" x:Name="cb">
  <ComboBoxItem>Combo</ComboBoxItem>
  <ComboBoxItem>Box</ComboBoxItem>
  <ComboBoxItem>Item</ComboBoxItem>
</ComboBox>

If I use

如果我使用

cb.Items.Contains("Combo")

or

或者

cb.Items.Contains(new ComboBoxItem {Content = "Combo"})

it returns False.

它返回False

Can anyone tell me how do I check if a ComboBoxItemnamed Comboexists in the ComboBoxcb?

谁能告诉我如何检查ComboBoxItem命名中是否Combo存在ComboBoxcb

采纳答案by Rohit Vats

Items is an ItemCollectionand not list of strings. In your case its a collection of ComboboxItemand you need to check its Contentproperty.

项目是一个ItemCollectionnot list of strings。在你的情况下是 a collection of ComboboxItem,你需要检查它的Content属性。

cb.Items.Cast<ComboBoxItem>().Any(cbi => cbi.Content.Equals("Combo"));

OR

或者

cb.Items.OfType<ComboBoxItem>().Any(cbi => cbi.Content.Equals("Combo"));

You can loop over each item and break in case you found desired item -

您可以遍历每个项目并在找到所需项目时中断 -

bool itemExists = false;
foreach (ComboBoxItem cbi in cb.Items)
{
    itemExists = cbi.Content.Equals("Combo");
    if (itemExists) break;
}

回答by Ming Slogar

If you want to use the Containsfunction as in cb.Items.Contains("Combo")you have to add strings to your ComboBox, not ComboBoxItems: cb.Items.Add("Combo"). The string will display just like a ComboBoxItem.

如果您想使用该Contains函数,cb.Items.Contains("Combo")您必须将字符串添加到 ComboBox,而不是 ComboBoxItems: cb.Items.Add("Combo")。该字符串将像 ComboBoxItem 一样显示。