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
?
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With