Chapter 6. Simple Data Binding

The purpose of most applications is to display data to users and, often, to let them edit that data. Your job as the application developer is to bring the data in from a variety of sources that expose their data in object, hierarchical, or relational format. Regardless of where the data comes from or the format it's in, there are several things that you'll most likely need to do with the data, including showing it, converting it, sorting it, filtering it, grouping it, relating one part of it to another part, and, more often than not, editing it. Without some kind of engine for shuttling data back and forth between data sources and controls, you're going to be writing a great deal of code. With WPF's data binding engine, you get more features with less code, which is always a nice place to be.

Without Data Binding

Consider a very simple application for editing a single person's name and age, as shown in Figure 6-1.

An exceedingly simple application

Figure 6-1. An exceedingly simple application

Figure 6-1 can be implemented with some simple XAML, as shown in Example 6-1.

Example 6-1. A simple Person editor layout

<!-- Window1.xaml -->
<Window ...>
  <Grid>

    ...
    <TextBlock ...>Name:</TextBlock>
    <TextBox Name="nameTextBox" ... />
    <TextBlock ...>Age:</TextBlock>
    <TextBox Name="ageTextBox" ... />
    <Button Name="birthdayButton" ...>Birthday</Button>
    </Grid>
    </Window>

We can represent the data to be shown ...

Get Programming WPF, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.