Monthly Archives: May 2011

Introduction to Templates–DataTemplate

Download the source code from here.

Most controls have some type of content, and that content often comes from data that you are binding to. In this sample, the data is the name and id of the student. In WPF, you use a DataTemplate to define the visual representation of data. Basically, what you put into a DataTemplate determines what the data looks like in the rendered application. For student name and id to be displayed  and highlighted, you create a DataTemplate as a resource:

            <DataTemplate DataType="{x:Type localXAMLClass:student}" >
                <Border BorderBrush="AliceBlue" BorderThickness="2">
                    <Grid Margin="10">
                        <TextBlock>
                            <Run Text="The Name of the student is "> </Run>
                            <TextBlock Background="LightBlue" Text="{Binding name}"></TextBlock>
                            <Run Text=" And his ID is "></Run>
                            <TextBlock Background="LightBlue" Text="{Binding id}" ></TextBlock>
                        </TextBlock>
                    </Grid>
                </Border>
            </DataTemplate>

Notice that the DataType property is very similar to the TargetType property of the Style. If your DataTemplate is in the resources section, when you specify the DataType property to a type and not assign it an x:Key, the DataTemplate is applied whenever that type appears. You always have the option to assign the DataTemplate with an x:Key and then set it as a StaticResource for properties that take DataTemplate types, such as the ItemTemplate property or the ContentTemplate property.

Before we dive into the data template used in the WPF application let’s see how a simple example works. First take a look at a simple class which represents a student:

namespace IntroductiontoTemplates1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class student
    {
        private string Name;
        private int Id;

        public string name
        {
            get{return Name;}
            set{Name = value;}
        }

        public int id
        {
            get { return Id;}
            set { Id = value; }
        }
    }
}

 

The student class contains two properties name and id. If we were to display an instance of this class in a ContentControl, the XAML would be something like this:

  1. <Window x:Class="IntroductiontoTemplates1.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
  4.         Title="MainWindow" Height="350" Width="525"
  5.         xmlns:localXAMLClass="clr-namespace:IntroductiontoTemplates1" >
  6.     <Grid>
  7.         <Grid.Resources>
  8.             <localXAMLClass:student x:Key="studentXAMLObject" name="kishore1021" id="1"></localXAMLClass:student>
  9.         </Grid.Resources>
  10.         <ContentControl
  11.             Content="{StaticResource studentXAMLObject}" >
  12.         </ContentControl>
  13.     </Grid>
  14. </Window>

 

The UI created by that XAML looks like the following:

image

That certainly isn’t too impressive. What you see above is what gets displayed as a result of calling ToString() on the student object referenced by the ContentControl. Let’s take a moment to examine what is going on here.

The example above creates an instance of the student class, which represents the student kishore1021. It also creates a ContentControl which is told to display that student object somehow. The ContentControl examines the student object and tries to figure out how to render it, but since student does not derive from UIElement it has no way of knowing how to do so. Once ContentControl is devoid of options, it ends up calling ToString() on the student object and then displays that text.

Override the inherited member Object.ToString() implementation.

        public override string ToString()
        {
            return "Returned from ToString() of student class";
        }

 

image

Now that we’ve seen how boring a student object looks in the absence of data templates, it’s time to add one into the mix. Here’s the same XAML used before, only this time there is a template for the student class:

            <DataTemplate DataType="{x:Type localXAMLClass:student}" >
                <Border BorderBrush="AliceBlue" BorderThickness="2">
                    <Grid Margin="10">
                        <TextBlock>
                            <Run Text="The Name of the student is "> </Run>
                            <TextBlock Background="LightBlue" Text="{Binding name}"></TextBlock>
                            <Run Text=" And his ID is "></Run>
                            <TextBlock Background="LightBlue" Text="{Binding id}" ></TextBlock>
                        </TextBlock>
                    </Grid>
                </Border>
            </DataTemplate>

 

Essentially, the DataTemplate in the above example defines that whenever there is a student class object, it should appear as the text “The name of the student is <xyz> And his ID is <322323>. With this DataTemplate, our application now looks like this:

 

image

That is how the XAML renders to show the proper data content: The student object is displayed much more intelligently when a data template is applied. The information held within it is now displayed as part of a sentence, and that sentence is wrapped in a curved blue border. Keep in mind that the rendition of a student object seen above is completely arbitrary. It can be displayed in whatever way is considered appropriate for the application in which it exists.

The complete code of the .cs file is as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace IntroductiontoTemplates1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class student
    {
        private string Name;
        private int Id;

        public string name
        {
            get{return Name;}
            set{Name = value;}
        }

        public int id
        {
            get { return Id;}
            set { Id = value; }
        }

        public override string ToString()
        {
            return "Returned from ToString() of student class";
        }

    }

}

The complete XAML code is as follows

<Window x:Class="IntroductiontoTemplates1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
        Title="MainWindow" Height="350" Width="525"
        xmlns:localXAMLClass="clr-namespace:IntroductiontoTemplates1" >
    <Grid>
        <Grid.Resources>
            <DataTemplate DataType="{x:Type localXAMLClass:student}" >
                <Border BorderBrush="Red" BorderThickness="2">
                    <Grid Margin="10">
                        <TextBlock>
                            <Run Text="The Name of the student is "> </Run>
                            <TextBlock Background="LightBlue" Text="{Binding name}"></TextBlock>
                            <Run Text=" And his ID is "></Run>
                            <TextBlock Background="LightBlue" Text="{Binding id}" ></TextBlock>
                        </TextBlock>
                    </Grid>
                </Border>
            </DataTemplate>

            <localXAMLClass:student x:Key="studentXAMLObject" name="kishore1021" id="1"></localXAMLClass:student>
        </Grid.Resources>
        
        <ContentControl
            Content="{StaticResource studentXAMLObject}" >
        </ContentControl>
    </Grid>
</Window>

 

Download the source code from here.

 

All men dream but not equally. Those who dream by night in the dusty recesses of their minds wake in the day to find that it was vanity; but the dreamers of the day are dangerous men, for they may act their dream with open eyes to make it possible. – T.E. Lawrence
Advertisements