Sometimes, you would like to get a combobox where a user can type. This can be done by turning on IsEditable property to true. However, it opens another can of worm, it means the user can type anything in the combobox even text that is not in the ItemsSource.
To provide LimitToList feature, you can hook up an event to PreviewLostKeyboardFocus as follows:
private void ComboBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (!e.Handled)
{
TextBox textBox = e.OldFocus as TextBox;
ComboBox comboBox = sender as ComboBox;
if (textBox != null && comboBox!=null)
{
DependencyObject common = comboBox.FindCommonVisualAncestor(e.NewFocus as DependencyObject);
// validate only the case when user step out of this control
if (common != comboBox)
{
bool invalid = !string.IsNullOrEmpty(textBox.Text) && comboBox.SelectedIndex < 0;
if (invalid)
{
e.Handled = true;
}
}
}
}
}
Later, I will show you how to create a visual clue to indicate that the combobox is invalid