Posted By

denakitan on 10/17/12


Tagged

Net basics examples WPF ComboBox c# itemssource


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

danfinrud55


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


 / Published in: C#
 

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

  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  

You need to login to post a comment.