Data Templates Redux

As you already know from Chapter 7, WPF allows you to define a data template, which is a tree of elements to expand in a particular context. We use data templates to provide an application with the capability to render nonvisual objects (see Example 8-21).

Example 8-21. Setting a PlayerMove data template without styles

<Window ... xmlns:local="clr-namespace:TicTacToe">


<Style TargetType="{x:Type Button}"> <Setter Property="HorizontalContentAlignment" Value="Stretch" /> <Setter Property="VerticalContentAlignment" Value="Stretch" /> <Setter Property="Padding" Value="8" /> </Style>

<DataTemplate DataType="{x:Type local:PlayerMove}">

<Grid> <TextBlock Text="{Binding Path=PlayerName}" FontSize ="32pt" FontWeight="Bold" VerticalAlignment="Center" HorizontalAlignment="Center" />

Example 8-21. Setting a PlayerMove data template without styles (continued)

<TextBlock Text="{Binding Path=MoveNumber}" FontSize="16pt" FontStyle="Italic" VerticalAlignment="Bottom" HorizontalAlignment="Right" /> </Grid> </DataTemplate> </Window.Resources>

Using the XAML mapping syntax described in Chapter 1, we've mapped the PlayerMove type into the XAML with the xmlns attribute, which we've used as the data type of the data template. Now, when a WPF element that uses the content model sees a PlayerMove object, like the content of all of our buttons, the data template will be expanded.* In our case, the template consists of a grid to arrange two text blocks, one showing the player name in the middle of the button and one showing the move number in the bottom right, along with some other settings to make things pretty. In addition, we've changed our button style to give the grid the entire space of the content area, less some padding around the edge (otherwise, things get a little cramped). Figure 8-9 shows the result.

Figure 8-9. Showing objects of a custom type using data templates and styles

* Controls that use the content model in WPF are those with control templates that use a ContentPresenter, as discussed in Chapter 9.

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook

Post a comment