Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a ComboBox Contains Item

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?

like image 880
Elmo Avatar asked Aug 10 '13 14:08

Elmo


2 Answers

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.

like image 160
Ming Slogar Avatar answered Oct 03 '22 08:10

Ming Slogar


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;
}
like image 29
Rohit Vats Avatar answered Oct 03 '22 08:10

Rohit Vats