Windows Phone 7.5 Data Cookbook
上QQ阅读APP看书,第一时间看更新

Data Templates

Data Templates are a very powerful feature in XAML. Data Templates can be reusable within element level or application level. In this recipe, let's use the Data Template in the listbox control.

Getting ready

Let's create a new project using the template Ch1_Recipe and rename it as Ch1_Recipe3.

How to do it...

  1. In this recipe we will give priority to the ListBox control.
  2. Open the MainPage.xaml file, locate the Grid with the name ContentPanel and add a TextBlock and a ListBox after the last text block control. The ListBox control will contain ItemTemplate in which DataTemplate is added.
    <!-- List box priority -->
    <TextBlock x:Name ="tbPriority" Text ="Priority:" Grid.Row="3" Grid.Column ="0" />
    
    <ListBox x:Name ="lstPriority" Grid.Row="3" Grid.Column ="1">
      <ListBox.ItemTemplate>
        <DataTemplate>
          <Border Name="border" BorderBrush="Red" BorderThickness="1" Padding="5" Margin="5">
    
            <StackPanel>
              <TextBlock x:Name ="tbPriorityContent" Text ="{Binding}" />
            </StackPanel>
          </Border>
        </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>
  3. Let's initialize the Listbox in the code behind the XAML file, MainPage.xaml.cs, using the ItemsSource property of the ListBox. ItemSource is a collection property. Add the following code inside the MainPage constructor before the initialization:
    lstPriority.ItemsSource = new string[] { "Low", "Medium", "High" };
  4. Press F5 to see how the ListBox is filled with Low, Medium, and High values. Also, notice how the ListBox behavior changes with the Border style.
    How to do it...

How it works...

A Data Template is the most flexible way to display data in XAML. It can include all the XAML controls like button, text blocks, textboxes, data grid, and so on. Here in the ListBox control, a Data Template is applied to all the items in the listbox along with all the formatting properties. We applied the Red border to the items in the DataTemplate mark-up.

There's more...

To understand more on Data Templates check the following article:

http://msdn.microsoft.com/en-us/library/ms742521.aspx

See also

Check the recipe named DataContext to understand more on data context concepts.