#396 – Rich ListBox Content Using Data Binding, part II
September 28, 2011 2 Comments
This post continues the example of displaying information about a series of movies in a ListBox, using data binding.
Last time, we showed the code for a Movie class, which stored data for a single movie.
The next step is to create some Movie instances and put them in a list, which we will then bind the ListBox to. We start by adding a property containing a list of movies, which we will bind to.
public ObservableCollection<Movie> MovieList { get; protected set; }
Next, we’ll add some code to set the data context of the main window to itself–which allows data binding GUI elements in the window to properties in the code-behind class that represents the window.
We also add code to the constructor to populate the list of movies.
public MainWindow() { this.InitializeComponent(); // Set data context of main window to itself, allowing to bind // elements in the GUI to properties in the code-behind. this.DataContext = this; // Populate movie list MovieList = new ObservableCollection<Movie>(); MovieList.Add(new Movie("King Kong", 1933, new Uri(@"..\Images\KingKong-1933.png", UriKind.Relative), "Bruce Cabot", "Fay Wray", "Merian C. Cooper")); MovieList.Add(new Movie("The Gay Divorcee", 1934, new Uri(@"..\Images\GayDiv-1934.png", UriKind.Relative), "Fred Astaire", "Ginger Rogers", "Mark Sandrich")); MovieList.Add(new Movie("Captain Blood", 1935, new Uri(@"..\Images\CptBlood-1935.png", UriKind.Relative), "Errol Flynn", "Olivia de Havilland", "Michael Curtiz")); MovieList.Add(new Movie("Modern Times", 1936, new Uri(@"..\Images\ModTimes-1936.png", UriKind.Relative), "Charlie Chaplin", "Paulette Goddard", "Charlie Chaplin")); MovieList.Add(new Movie("Topper", 1937, new Uri(@"..\Images\Topper-1937.png", UriKind.Relative), "Cary Grant", "Constance Bennett", "Norman Z. McLeod")); OnPropertyChanged("MovieList"); }
Pingback: Dew Drop – September 28, 2011 | Alvin Ashcraft's Morning Dew
Pingback: Link Resource # 27 : Oct 03 – Oct 06 « Dactylonomy of Web Resource