1. Back To Blog

What is the difference between control templates and data templates? ( .NET WPF Interview questions)

Download 100 WPF Interview questions with answer from here.


Control templates change the structure of a WPF element while data templates change the way data is displayed but maintain the structure of WPF element.


Below is a visual example of control template where a rectangle shaped button is change in to an ellipse shape.




For that we need to create style using the "" element. In this "" WPF element we can define the structure which we want to apply on the element. Below is the XAML code for the same.


<Style TargetType="Button">

<!--Override all default style -->

<Setter Property="OverridesDefaultStyle" Value="True"/>

<Setter Property="Template">

<Setter.Value>

<ControlTemplate TargetType="Button">

<Grid>

<Ellipse Fill="TemplateBinding Background}"/>

<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>

</Grid>

</ControlTemplate>

</Setter.Value>

</Setter>

</Style>


Later this style can be applied to the button using the style property as shown in below code.


<Button Style="StaticResource mystyle}" />


Data templates have no effect on the structure but they affect data. For example below is list box on which data templates have been applied. You can see the structure of the list box does not change but the number of fields and the way they are placed is changed.



To use data templates we need to use 'ItemTemplate" tag and within the "ItemTemplate" tag we can define the how we want the data to be structured.


<ListBox Margin="26,27,165,51" x:Name="lstb">

<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>

</ListBox>


Below is a nice WPF interview question video which explains Why WPF is better than winforms ?


Shiv Prasad Koirala

Visit us @ www.questpond.com or call us at 022-66752917... read more

We are on Social