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.

Advertisements

~ by Martin on October 13, 2008.

One Response to “ControlTemplate and DataTemplate”

  1. Hi Martin, thanks for your wonderful and brief explanation. I added this page to my bookmarks under “WPF’s Golden Rules”.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: