ControlTemplate and DataTemplate

Sometimes it seems that some elements can be placed in the ControlTemplate, and also can be placed in the DataTemplate. This causes great confustion for WPF beginners. But actually there is a clear line between the both, and it is not that some elements can be placed in either of them.

ControlTemplate reflects the behaviors and appearance of a control. It should not have knowledge of the content(data), if it has, because the data is wrapped and represented by ContentPresenter/ItemsPresenter in the ControlTemplate.

DataTemplate is the representation of the data. Similarly, DataTemplate should not have knowledge of its residing control, because DataTemplate only represents the data, and can be placed in any ContentControl.

Karl said :”When authoring your control, attempt to design a control that derives its behavior and appearance from its own dependency properties.” This means that dependencyproperty is designed for its control’s behaviors and apperance, NOT for its content(data)’s behaviors and apperance. All the dependencyproperty-related behaviors and appearance should be defined in the ControlTemplate, whereas all the data-related behaviors and appearance should be defined in the DataTemplate. Note: By Data here I mean Content’s data.

This actually makes up a rule for the default ControlTemplate of the custom control:
When working on the default ControlTemplate for the custom control, do NOT involve DataTemplate, because you do not know what the content(data) will be and how it will be represented. The content(data) is just abstracted as ContentPresenter/ItemsPresenter in the ControlTemplate.


From: http://wangmo.wordpress.com/2008/10/13/controltemplate-and-datatemplate/

Comments

Popular Posts