Data Binding
Once we've got a set of controls and a way to lay them out, we still need to fill them with data and keep that data in sync with wherever the data actually lives. (Controls are a great way to show data but a poor place to keep it.) For example, imagine that we'd like to build a WPF application for keeping track of people's nicknames. Something like Figure 1-15 would do the trick.

Figure 1-15. Data binding to a collection of custom types
In Figure 1-15,
we've got two TextBox controls, one
for the name and one for the nickname. We've also got the actual
nickname entries in a ListBox in the
middle and a Button to add new
entries. We could easily build the core data of such an application with
a class, as shown in Example 1-25.
Example 1-25. A custom type with data binding support
public class Nickname : INotifyPropertyChanged {
// INotifyPropertyChanged Member
public event PropertyChangedEventHandler PropertyChanged;
void Notify(string propName) {
if( PropertyChanged != null ) {
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
string name;
public string Name {
get { return name; }
set {
name = value;
Notify("Name"); // notify consumers
}
}
string nick;
public string Nick {
get { return nick; }
set {
nick = value;
Notify("Nick"); // notify consumers } } public Nickname( ) : this("name", "nick") { } public Nickname(string name, string nick) { this.name ...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