Check if a ComboBox Contains Item

.net, c#, combobox, wpf, xaml

Solution

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.

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;
}

Problem

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`. Can anyone tell me how do I check if a `ComboBoxItem` named `Combo` exists in the `ComboBox` `cb`?

Original source