There is a ComboBox, in which 2 elements.
How can I check what the user has chosen?
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 - выбранный отдел, делаем с ним что хотим. } } CompositeCollection (like this ). - VladDSource: https://ru.stackoverflow.com/questions/445353/
All Articles