Difference between Control Template and DataTemplate in WPF
Typically a control is rendered for its own sake, and doesn't reflect underlying data. For example, a Button
wouldn't be bound to a business object - it's there purely so it can be clicked on. A ContentControl
or ListBox
, however, generally appear so that they can present data for the user.
A DataTemplate
, therefore, is used to provide visual structure for underlying data, while a ControlTemplate
has nothing to do with underlying data and simply provides visual layout for the control itself.
A ControlTemplate
will generally only contain TemplateBinding
expressions, binding back to the properties on the control itself, while a DataTemplate
will contain standard Binding expressions, binding to the properties of its DataContext
(the business/domain object or view model).
Very basically a ControlTemplate
describes how to display a Control while a DataTemplate
describes how to display Data.
For example:
A Label
is a control and will include a ControlTemplate
which says the Label
should be displayed using a Border
around some Content (a DataTemplate
or another Control).
A Customer
class is Data and will be displayed using a DataTemplate
which could say to display the Customer
type as a StackPanel
containing two TextBlocks
one showing the Name and the other displaying the phone number. It might be helpful to note that all classes are displayed using DataTemplates
, you will just usually use the default template which is a TextBlock
with the Text
property set to the result of the Object's ToString
method.