/ Published in: C#
Snippet to illustrate how to bind a ComboBox to a Dictionary.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// creating a dictionary of ghibli movie names by release year ghibliMovies.Add(1997, "Princess Mononoke"); ghibliMovies.Add(1995, "Whisper of the Heart"); ghibliMovies.Add(2001, "Spirited Away"); // creating a sorted list of release years releaseYears.Sort(); // creating and populating the dictionary to act as the ComboBox ItemsSource foreach (int year in releaseYears) { comboBoxItemsSource.Add(year, ghibliMovies[year]); } // setting the ItemsSource of the ComboBox and selecting the latest movie // each item will display the movie name and its selected value will be the movie's release year cbGhibliMovies.ItemsSource = comboBoxItemsSource; cbGhibliMovies.DisplayMemberPath = "Value"; cbGhibliMovies.SelectedValuePath = "Key"; cbGhibliMovies.SelectedIndex = cbGhibliMovies.Items.Count - 1;