#965 – ListBox Data Binding Basics, part II
December 5, 2013 2 Comments
Assume that we want to use a ListBox to display a list of actors. We can start by creating an Actor type that stores various information about an actor. We want the class to implement the INotifyPropertyChanged interface, so that data binding client are notified of changes to any properties.
Full code for Actor.cs is shown below. Note that when we change FullName, BirthYear or DeathYear properties, we also flag the derived NameAndDates property as potentially changed.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; namespace WpfApplication2 { public class Actor : INotifyPropertyChanged { public Actor() { } public Actor(string fullName, int? birthYear, int? deathYear, string knownFor, Uri image) { FullName = fullName; BirthYear = birthYear; DeathYear = deathYear; KnownFor = knownFor; Image = image; } private string fullName; public string FullName { get { return fullName; } set { fullName = value; RaisePropertyChanged("FullName"); RaisePropertyChanged("NameAndDates"); } } private int? birthYear; public int? BirthYear { get { return birthYear; } set { birthYear = value; RaisePropertyChanged("BirthYear"); RaisePropertyChanged("NameAndDates"); } } private int? deathYear; public int? DeathYear { get { return deathYear; } set { deathYear = value; RaisePropertyChanged("DeathYear"); RaisePropertyChanged("NameAndDates"); } } private string knownFor; public string KnownFor { get { return knownFor; } set { knownFor = value; RaisePropertyChanged("KnownFor"); } } private Uri image; public Uri Image { get { return image; } set { image = value; RaisePropertyChanged("Image"); } } public string NameAndDates { get { string result = FullName; if (BirthYear.HasValue) { if (DeathYear.HasValue) result = result + string.Format(" ({0}-{1})", BirthYear.Value, DeathYear.Value); else result = result + string.Format(" ({0}- )", BirthYear.Value); } return result; } } // INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged = delegate { }; private void RaisePropertyChanged(string propName) { PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } }