Chapter 7. Binding to List Data
In Chapter 6, we looked at the basics of data binding with respect to single objects. However, when you've got lists of objects, you've got still more flexibility and power, including managing the "current" object in a list, sorting, filtering, and grouping. Also, WPF gives you the ability to expand a single data source object into a set of target UI elements with data templates, bring in XML and relational data, and perform master-detail binding and hierarchical binding. We discuss all of these topics in this chapter.
Binding to List Data
To kick things off, recall our Person class from Chapter 6; let's add a new type for keeping track
of a list of Person objects (see
Example 7-1).
Example 7-1. Declaring a custom list type
using System.Collections.Generic; // List<T>
...
namespace PersonBinding {
public class Person : INotifyPropertyChanged {
// INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void Notify(string propName) {
if( this.PropertyChanged != null ) {
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
string name;
public string Name {
get { return this.name; }
set {
if( this.name == value ) { return; }
this.name = value;
Notify("Name");
}
}
int age;
public int Age {
get { return this.age; }
set {
if(this.age == value ) { return; }
this.age = value;
Notify("Age");
}
}
public Person( ) {}
public Person(string name, int age) {
this.name = name;
this.age = age;
}
} // Create an alias ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access