Software & Finance





WPF - Difference Between ControlTemplate and DataTemplate





Control Template would work on changing the appearance, image and other custom drawing on the element. Data Template works with the data using those elements.

 

Here is the example of ItemTemplate that applies to ListBox with two text blocks on each listbox item.

 

<Style x:Key="PlusMarkButton"

           BasedOn="{x:Null}"

           TargetType="{x:Type Button}">

    <Setter Property="Template">

         <Setter.Value>

            <ControlTemplate TargetType="{x:Type Button}">

               <Grid>

                   // Custom Drawing, background color, etc goes here

               </Grid>

            </ControlTemplate>

         </Setter.Value>

      </Setter>

</Style>

 

Here is an example of DataTemplate that deals with changing the data

 

<ListBox.ItemTemplate>

   <DataTemplate>

      <Grid>

         <Grid.ColumnDefinitions>

            <ColumnDefinition Width="150"></ColumnDefinition>

            <ColumnDefinition Width="*"></ColumnDefinition>

         </Grid.ColumnDefinitions>

 

         <TextBlock Grid.Column="0" Text="{Binding Name}"  FontSize="12" Height="18" />

         <TextBlock Grid.Column="1" Text="{Binding City}"  FontSize="12" Height="18" />

 

      </Grid>

   </DataTemplate>

</ListBox.ItemTemplate>