There is a ComboBox, in which 2 elements.

How can I check what the user has chosen?

  • Binding the SelectedItem to the appropriate property of your VM, of course. - VladD
  • @VladD, can you give an example? - andrew
  • I'll write now, a moment. - VladD

2 answers 2

Here is an example:

VM Level:

class Entry { public string Name { get; set; } } class VM : INotifyPropertyChanged { public ObservableCollection<Entry> Entries { get; private set; } Entry selectedEntry; Entry SelectedEntry { get { return selectedEntry; } set { selectedEntry = value; NotifyPropertyChanged(); } } } 

View level:

 <ComboBox ItemsSource="{Binding Entries}" DisplayMemberPath="Name" SelectedItem="{Binding SelectedEntry}"/> 

    I agree with the answer @VladD, but there is another, "worker-peasant" method through the Tag property of the ComboboxItem element, which is very useful when direct Binding to data is inconvenient (For example, you need to add the first element "All options", which, of course, is not Binding Source):

      //заполнение первого элемента ComboBoxItem first_cbi = new ComboBoxItem(); first_cbi.Content = "Все отделы"; cb_Departments.Items.Add(first_cbi); //заполнение остальных элементов из чего-нибудь IEnumerable foreach (Department dep in Departments) { ComboBoxItem cbi = new ComboBoxItem(); cbi.Tag = dep; cbi.Content = dep.Name; cb_Departments.Items.Add(cbi); } //-- //Обработчик выбора элемента private void cb_Departments_SelectionChanged(object sender, SelectionChangedEventArgs e) { if(cb_Departments.SelectedIndex=0) { //выбрана опция "Все отделы" } else { ComboBoxItem cbi=(ComboBoxItem)cb_Departments.SelectedItem; Department selectedDepartment=(Department)cbi.Tag; //selectedDepartment - выбранный отдел, делаем с ним что хотим. } } 
    • one
      For such purposes, it is better to use a CompositeCollection (like this ). - VladD