.NET - WPF - C# - Basics - Examples - ComboBox ItemsSource Definition


/ Published in: C#
Save to your folder(s)

Snippet to illustrate how to bind a ComboBox to a Dictionary.


Copy this code and paste it in your HTML
  1. // creating a dictionary of ghibli movie names by release year
  2. Dictionary<int, string> ghibliMovies = new Dictionary<int, string>();
  3. ghibliMovies.Add(1997, "Princess Mononoke");
  4. ghibliMovies.Add(1995, "Whisper of the Heart");
  5. ghibliMovies.Add(2001, "Spirited Away");
  6.  
  7. // creating a sorted list of release years
  8. List<int> releaseYears = new List<int>(ghibliMovies.Keys);
  9. releaseYears.Sort();
  10.  
  11. // creating and populating the dictionary to act as the ComboBox ItemsSource
  12. Dictionary<int, string> comboBoxItemsSource = new Dictionary<int, string>();
  13. foreach (int year in releaseYears)
  14. {
  15. comboBoxItemsSource.Add(year, ghibliMovies[year]);
  16. }
  17.  
  18. // setting the ItemsSource of the ComboBox and selecting the latest movie
  19. // each item will display the movie name and its selected value will be the movie's release year
  20. cbGhibliMovies.ItemsSource = comboBoxItemsSource;
  21. cbGhibliMovies.DisplayMemberPath = "Value";
  22. cbGhibliMovies.SelectedValuePath = "Key";
  23. cbGhibliMovies.SelectedIndex = cbGhibliMovies.Items.Count - 1;

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.