I have a combobox with names in it. I have the box set to editable so that the user can enter a name. I want it so that the user can only enter a name that is already in the list. When the user clicks save I want the box to have the red validation border show up if the box is empty or not in the list. Is there a way to do this?
<ComboBox IsEditable="True"
Grid.Column="2"
Grid.Row="1"
Margin="5,3,0,0"
Text="{Binding Model.Number}"
ItemsSource="{Binding DList}"
SelectedItem="{Binding Model.Number}"
IsEnabled="{Binding EnableComboBox}"
VerticalAlignment="Top">
</ComboBox>
If I understood correctly, you want the user to be able to select an existing list item by typing, but not type a string that is not on the list. That can be done with the following:
<ComboBox IsEditable="False"></ComboBox>
This will allow the user to start typing the string, but you lose the textbox for input.
Another way to do it is to allow the user to type whatever they want by setting <ComboBox IsReadOnly="False" IsEditable="True">
and handle for example the LostFocus
event to check if the input is valid. Here's an example:
private void ComboBox_LostFocus(object sender, RoutedEventArgs e)
{
bool allowed = false;
foreach (ComboBoxItem it in comboBox.Items)
{
if (it.Content.ToString() == comboBox.Text)
{
allowed = true;
break;
}
}
if (!allowed)
{
MessageBox.Show("MISS!");
}
else
{
MessageBox.Show("HIT!");
}
}
For some reason I wasn't able to set the border color quickly, but you get the point from here. Also depending on your ComboBoxItem
type, you may need to match the comboBox.Text
to a certain property.
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