So I have a ComboBox with a binding to a DataSet and I want an event to fire only when the selection is changed. I tried to use the SelectionChanged event but it fires whenever there is a suggested item. For instance if I type "eb" then "ebtoulson" would be selected with the "toulson" highlighted. My question is how would I disable this event from firing on the suggestion or am I using the wrong event? Any suggestions would be much appreciated.
2 Answers
0
votes
0
votes
I have come up with this solution. I don't feel it is the most optimal, but it covers your case. I'm using PreviewTextInput
event to handle selection via text entry, and DropDownClosed
to handle selection via the mouse. My ComboBox
control is named cbTest1
, and the code I've used is as follows:
private void cbTest1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
var q = from i in cbTest1.ItemsSource.Cast<ComboBoxItem>()
where ((string)i.Content).StartsWith(e.Text, StringComparison.OrdinalIgnoreCase)
select i;
if (q.Count() == 1)
{
// Have typed out a unique name match.
var ActiveItem = cbTest1.SelectedItem;
}
else
{
// Name does not match or has multiple matches.
}
}
private void cbTest1_DropDownClosed(object sender, EventArgs e)
{
var ActiveItem = cbTest1.SelectedItem;
}
It uses the Linq expression to determine if what the user has typed thus far has narrowed the selections down to a single item. However, the cost of that query may be too high for your case. Just try it out and let me know.