Both controltemplate and datatemplate are used to customize the appearance of the control, but there is a big difference between them.
Controltemplate serves control (tangible control), while datatemplate serves data (intangible data ).
In other words, controltemplate is used to transform the existing appearance, and datatemplate is used to build the appearance from scratch.
Contentcontrol and itemscontrol
- Contentcontrol, whose content attribute contains a single element, such as button
- Itemscontrol, whose items attributes contain multiple elements, such as ListBox
Contentpresenter and itemspresenter types
In normal use, we can think of these presenters as placeholders. They are used in the definition of controltemplate, representing the original content of the control.
Taking contentcontrol as an example, it has a contentpresenter type attribute. If its value is a uielement, this uielement is directly displayed, but if it is an invisible data, the value of contentpresenter must be a ememplate.
Controltemplate type
Controltemplate representative:
- Contentcontrol type template attribute
- Itemscontrol type template attribute
{Templatebinding attribute name} is often seen in the controltemplate type, which generally indicates binding to the attributes of the original control.
Datatemplate type
Typical datatemplate:
- Contenttemplate attribute of contentcontrol type
- Itemtemplate attribute of itemscontrol type
{Binding…} is often seen in the datatemplate type ...}, Indicates data binding.
The following does not belong to the template, but often appears together with the template, so it is written here.
Itemspanel type
The layout of items in itemscontrol, which is commonly used by stackpanel.
Itemcontainerstyle type
Customizes the style of each item in itemscontrol. If you want to customize the style of the itemscontrol framework, you can directly use the style attribute of itemscontrol.
My experience
Datatemplate is more commonly used than controltemplate.
To understand the template (controltemplate type) of a control, you need to use blend to view the visual tree of the control. However, in some cases, using controltemplate is very efficient. For example, you can change all textbox to a rounded corner and add an image to the button shape. Controltemplate is required for the transformation of the bones and muscles, while for general tracing (new value for existing attributes), you only need to assign values to the attributes to be changed in the setter of the style.