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
Check if a ComboBox Contains Item
提问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 ComboBoxItem
named Combo
exists in the ComboBox
cb
?
谁能告诉我如何检查ComboBoxItem
命名中是否Combo
存在ComboBox
cb
?
采纳答案by Rohit Vats
Items is an ItemCollection
and not list of strings
. In your case its a collection of ComboboxItem
and you need to check its Content
property.
项目是一个ItemCollection
和not 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 Contains
function 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 一样显示。