Handling WPF Editable combobox when entered text is not a part of datsource

12,922

You can check for selectedIndex in Lostfocus event :

private void ComboBox_LostFocus(object sender, EventArgs e)
{
    if(((ComboBox)sender).SelectedIndex == -1)
    {
        //Text entered by user is not a part your ItemsSource's Item
        SaveButton.IsEnabled = false; 
    }
    else
    {
        //Text entered by user is a part your ItemsSource's Item
        SaveButton.IsEnabled = true;
    }
}
Share:
12,922
Arti
Author by

Arti

Updated on June 04, 2022

Comments

  • Arti
    Arti almost 2 years

    I have a Combobox in WPF, I have set Is Editable="true" which allows me enter any text in the combobox. I would like to restrict users from entering text outside datasource.

    Xaml:

    <ComboBox Name="service" Margin="0,0,0,4" 
        IsEditable="True"
        Grid.Column="1" 
        Grid.ColumnSpan="2" Grid.Row="4" 
        SelectedValuePath="Id" 
        DisplayMemberPath="Service" 
        SelectedValue="{Binding Controller.Service1}" 
        ItemsSource="{Binding}" />
    

    C#:

    System.Data.DataView vw = tableAdapterServices.GetData().DefaultView;
    service.ItemsSource = vw;
    service.SelectedIndex = 0;
    

    I do not want to allow users to enter text which is not present in the datasource, or handle it if the user enters any other text.

    Update:

    Thanks for the solution @Vishal, LostFocus event is handling the issue, but it gave rise to another issue. I have a button which is used to submit the combobox value along with other textbox values to the server. I am setting default value in the combobox in lostfocus event. But I need to prevent the button click event if some value other that datasource value is added in combobox.

  • Arti
    Arti almost 10 years
    I am new to WPF. Yes, I am using MVVM style. I am getting error The attachable property 'Triggers' was not found in type 'Interaction'. when i use the you xaml.