Return to Snippet

Revision: 60029
at October 17, 2012 08:06 by denakitan


Initial Code
// creating a dictionary of ghibli movie names by release year
Dictionary<int, string> ghibliMovies = new Dictionary<int, string>();
ghibliMovies.Add(1997, "Princess Mononoke");
ghibliMovies.Add(1995, "Whisper of the Heart");
ghibliMovies.Add(2001, "Spirited Away");

// creating a sorted list of release years
List<int> releaseYears = new List<int>(ghibliMovies.Keys);
releaseYears.Sort();

// creating and populating the dictionary to act as the ComboBox ItemsSource
Dictionary<int, string> comboBoxItemsSource = new Dictionary<int, string>();
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;

Initial URL


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

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

Initial Tags
Net, c#

Initial Language
C#