Search code examples
c#wpfmvvmcomboboxwcf-binding

binding an editable combobox and detect inserted text in wpf


I have a ComboBox that it looks like this:

<ComboBox
    ItemsSource="{Binding JobList}"
    SelectedValue="{Binding Job,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"
    DisplayMemberPath="Title"
    SelectedValuePath="Id"
    IsEditable="True"
    StaysOpenOnEdit="True"
    />

and its binding to my ViewModel that looks like this one:

public class ViewModel {
    // this will fill from a database record for a person
    public Job Job {
        get { return _job; }
        set {
            if(value == _job) return;
            _job = value;
            OnPropertyChanged( () => Job );
        }
    }
    // this will fill from all jobs records in database
    public ObservableCollection<Job> JobList 
    { /* do same as Job to implementing INotifyPropertyChanged */ }
}

and the Job is:

public class Job {
    public int Id { get; set; }
    public string Title { get; set; }
}

Really, I want to fill the ComboBox with job's list. So if the user's specified Job was in list, user can select it from list, otherwise, he enter a new Job.Title in ComboBox, the view model notify on it, and create a new Job item and also add it to JobList.

Have you any idea? can you help me please?


Solution

    1. Create a string property in the viewModel something like 'SelectedJobName'
    2. Bind this property to Combobox.Text
    3. Wherever you want to use the entered value (Command, Presenter), check if selected value is not null and selectedJobName property value is not/matching.