Build an Open Data App – Part 4: Binding the Data

Binding is when you take data and push it to your UI. A classic example is showing a user’s name when they’ve logged in. It’s not hardcoded into the UI, you change it based on differing criteria. In the case of this app, we’re going to show a list of Bike Share stations in Toronto, Canada. For this example, we’ll build the UI in the shared app, using XAML.

In order to accomplish this, we need to setup a few things:

  1. A ListBox in XAML.
  2. A template for the data to display.
  3. The page’s DataContext must be set.

In the page’s CS code, you’ll want to override the OnNavigatedTo method. The reason is that, like all constructors, you can’t do async work in the page constructor and we need async to await the data model’s LoadData method.

The result will look like this.

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    await MainDataModel.Instance.LoadData();
    this.DataContext = MainDataModel.Instance;
}

Early in this series I mentioned an Initialized action. In our case we don’t need it as the dataset will load fast enough, but you could set up the event handlers here for that if you’d like.

Next, we need to setup the XAML to have the bindings to display the data.

<ListBox ItemsSource="{Binding BikeStations}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <ListBoxItem>
                <TextBlock Text="{Binding StationName}"/>
            </ListBoxItem>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

What’s happening here is that we’re setting the ListBox‘s ItemsSource which holds the collection of items to be displayed. All bindings are relative. As the page’s DataContext is the MainDataModel we can merely state which property we want to connect. Similarly, the ListBoxItem‘s bindings are relative to the ItemsSource of the ListBox, and so on. You’ll notice each of these are targeting properties. If you were to make a plain string the binding’s target, it simply won’t work. If you find your bindings failing, check that first.

This entry was posted in .NET, Building an Open Data App, Open Data, Windows 8, Windows 8.x, Windows Phone and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s