To check if a value is inside a collection or not, you will always need to perform some check. In this case, you need a collection that can check for a unique value very fast. What you need is a
HashSet<string>
collection, which uses binary search. For example:
private readonly var _comboItems = new Lazy<HashSet<string>>(
() => new HashSet<string>(StringComparer.OrdinalIgnoreCase));
Then, use this collection in a property and provide it as the
ItemsSource
of the
ComboBox
. Like this:
public ISet<string> ComboItems => _comboItems.Value;
<ComboBox ItemsSource="{Binding ComboItems}"/>
You would populate the items collection from the database by using the property.
ComboItems.Add(myDatabaseItem);
Remember that, because HashSet doesn't provide notification events, WPF doesn't know when the collection is changed, so you need to populate the collection before the
ComboBox
is instantiated, or you need to re-set
ItemsSource
property again, by setting it to
null
and then to
ComboItems
again. If you want to decouple your C# code from XAML objects (recommended), you can instead access the
CollectionView
for your collection and request that it is updated. Like the following:
var collectionView = CollectionViewSource.GetDefaultView(ComboItems);
collectionView?.Refresh();
When you need to determine if a specific item exists on the ComboItems collection, you would need just the following code:
string textToCheck = "Item you want to check";
if (string.IsNullOrWhiteSpace(texToCheck))
{
}
else if (ComboItems.Contains(textToCheck.Trim()))
{
}
else
{
}