Megosztás a következőn keresztül:


Displaying Data with Data Binding

October 21, 2011

Once you have created pages for your Windows Phone application, you will want to populate those pages with data using data binding.

You Will Learn

  • How to bind data to the UI.
  • How to use Visual Studio to help you bind to data.
  • How to display data in a list.
  • How to work with more complex binding scenarios.

Applies To

  • Silverlight for Windows Phone OS 7.1

    Gg680271.d3275827-f0d6-4a71-9a28-8e103800b08a(en-us,PandP.11).png

Binding Data to UI

The Fuel Tracker application has three pages that display data. The data is stored primarily in three classes. The following illustration shows the pages and associated data classes.

Gg680271.2fcad323-afa9-4398-ae27-59c99e896e17(en-us,PandP.11).png

To display data, you typically use data binding. Data binding provides a way to connect a data source to the UI. When a binding is established and the data source changes, the UI elements that are bound to the data source can reflect changes automatically. Similarly, changes made by the user in a UI element can be reflected in the data source. For example, if the user edits the value in a TextBox, the underlying data source is automatically updated to reflect that change.

The bindings are set directly to the appropriate data classes, which have float properties. On save, the entered values persist only if they can be parsed as floats. For more information, see Validating Data Entry Input.

The following XAML shows the syntax that you use to bind the Text property of a TextBox to the Name property of a source object.

<TextBox Grid.Row="0" Grid.Column="1" x:Name="NameTextBox" 
         Text="{Binding Name, Mode=TwoWay" MaxLength="20" />

The following illustration shows an example of this binding.

Gg680271.72a502f1-64a7-462b-b9a5-7896ce002a9b(en-us,PandP.11).png

Each binding has a Mode property that specifies how and when the data is updated. OneWay binding means that the target is updated if the source changes. TwoWay binding means that both the target and the source are updated if either change. If you use OneWay or TwoWay bindings, in order for the binding to be notified of changes to the source object, you must implement the INotifyPropertyChanged interface. This interface is discussed further in Creating Data Classes.

You specify the source object by setting the DataContext property. If you are using a ListBox control, you specify the source object by setting the ItemsSource property. The following example demonstrates setting the DataContext property of a CarHeader panel to a source object retrieved from a static property.

CarHeader.DataContext = CarDataStore.Car;
CarHeader.DataContext = CarDataStore.Car

The DataContext property lets you set the default binding for an entire UI element, including all of its child elements. In some cases, you will set the DataContext property for an entire page, and in other cases, you will set it for individual elements on the page. The DataContext setting at each XAML level overrides any settings at a higher level. Additionally, you can override any DataContext setting in effect for an individual binding by setting its Source property.

In the Fuel Tracker application, for example, each page sets its DataContext to a different value. On the FillupPage, however, the page-level DataContext is overridden for the panel that displays the car name and photo. The following illustration shows the data context settings in Fuel Tracker.

Gg680271.74200203-7dc0-4f38-ba4d-b668d4707e52(en-us,PandP.11).png

For more information about data binding, see the Data Binding to Controls QuickStart and Data Binding.

Using the Data Binding Builder

Visual Studio includes a data binding builder to help you create data bindings in XAML. Although the data binding builder can provide a productivity boost, it doesn’t support all scenarios. For example, it doesn’t support binding to indexed items and it doesn’t recognize bindings created in code. Therefore, in some cases, you will need to specify data bindings manually.

To use the data binding builder

  1. Select the control that you want to set a binding for.

  2. In the Properties window, find the property that you want to bind.

  3. At the edge of the left column, click the property marker icon and then click Apply Data Binding.

    The data binding builder appears.

  4. Click the various panes in the data binding builder to expand the different options.

    The following illustration shows the data binding builder with the following settings:

    • Data context: Fillup object
    • Binding path: OdometerReading property
    • Mode: TwoWay

Gg680271.ccb5b306-42c6-4876-92c4-0f1b4df5dcf7(en-us,PandP.11).png

The following example shows the XAML that is generated by the data binding builder.

<TextBox Grid.Row="0" Grid.Column="1" x:Name="OdometerTextBox" 
    Text="{Binding OdometerReading, Mode=TwoWay, StringFormat=\{0:#\}}" 
    InputScope="Number" MaxLength="8" />

Note

When you set the DataContext property in code, the data binding builder has no knowledge of the properties available on the data source, and can’t help you choose the binding path. However, you can fix this problem by setting a design-time data context. For information about setting a design-time data context, see Walkthrough: Using a DesignInstance to Bind to Data in the Silverlight Designer.

For more information about the data binding builder, see Data Binding in the Silverlight Designer.

Displaying Data in a List

Displaying a collection of items in a list is a common task on the phone. To display a collection of items in a list by using data binding, you typically do the following:

  1. Add a ListBox to your application.
  2. Specify the data source for the ListBox by binding the collection to the ItemsSource property.
  3. To customize the look of each item in the ListBox, add a data template to the ListBox.
  4. In the data template, bind elements of a ListBox item to properties of a collection item.

The following illustration shows the bindings for the ListBox in the summary page of the Fuel Tracker application.

Gg680271.deb68063-dbea-47ad-9aa5-2f5597b01457(en-us,PandP.11).png

The following XAML shows how the bindings were specified for the ListBox.

<ListBox ItemContainerStyle="{StaticResource ListBoxStyle}"
    ItemsSource="{Binding FillupHistory}" 
    Height="380" HorizontalAlignment="Left" Margin="5,25,0,0" 
    VerticalAlignment="Top" Width="444" >
    <ListBox.ItemTemplate>
      <DataTemplate>
       <StackPanel Orientation="Horizontal">
         <TextBlock Style="{StaticResource SummaryStyle}" 
            Text="{Binding Date, StringFormat=\{0:d\} }"
            Width="105" TextWrapping="Wrap"/>
         <TextBlock Style="{StaticResource SummaryStyle}" 
            Text="{Binding FuelQuantity}" TextWrapping="Wrap" />
         <TextBlock Style="{StaticResource SummaryStyle}" 
            Text="{Binding DistanceDriven}" TextWrapping="Wrap" />
         <TextBlock Style="{StaticResource SummaryStyle}"  
            Text="{Binding PricePerFuelUnit, StringFormat=\{0:c\} }" />
         <TextBlock Style="{StaticResource SummaryStyle}" 
            Text="{Binding FuelEfficiency, StringFormat=\{0:F\}}" 
            TextWrapping="Wrap"  />
       </StackPanel>    
      </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

In the previous XAML, the ListBox.ItemsSource property is bound to the Car.FillupHistory property so that each Fillup object in the history collection will appear as a separate item in the ListBox. The DataTemplate element defines the appearance of each item, and contains several TextBlock elements, each bound to a property of the Fillup class.

This XAML will work only if a Car object is first associated with the page, as shown in the following code from the SummaryPage class.

DataContext = CarDataStore.Car;
DataContext = CarDataStore.Car
Gg680271.note(en-us,PandP.11).gifPerformance Tips:
If scrolling in your ListBox isn’t smooth and responsive, consider the following tips:
Simplify the items in the ListBox.
Load images in the background.
Use data virtualization.
Investigate using DeferredLoadListBox or LazyListBox.
Do not use nested list boxes.
For more information, see Silverlight for Windows Phone 7: ListBox Scroll Performance.

For more information about binding to a collection and data templates, see the Data Binding to Controls QuickStart, Data Binding, and How to: Customize Data Display with Data Templates.

Next Topic | Previous Topic | Home