Skip to Main Content
Programming WPF, 2nd Edition
book

Programming WPF, 2nd Edition

by Chris Sells, Ian Griffiths
August 2007
Intermediate to advanced content levelIntermediate to advanced
864 pages
25h 52m
English
O'Reilly Media, Inc.
Content preview from Programming WPF, 2nd Edition

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.

Data binding to a collection of custom types

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.
Start your free trial

You might also like

Programming C#, 4th Edition

Programming C#, 4th Edition

Jesse Liberty
Programming C# 10

Programming C# 10

Ian Griffiths

Publisher Resources

ISBN: 9780596510374Supplemental ContentErrata Page