Showing posts with label wpf controltemplate datatemplate hierarchicaldatatemplate treeview. Show all posts
Showing posts with label wpf controltemplate datatemplate hierarchicaldatatemplate treeview. Show all posts

Thursday, February 10, 2011

ControlTemplate vs DataTemplate

When to use ControlTemplate and when to use DataTemplate/HierarchicalDataTemplate
Quick Answer:
- ControlTemplate is used to replace the whole visual tree of a control.
- DataTemplate/HierarchicalDataTemplate: is used only to replace the content of a control.
Example at the bottom will clarify more.

Features of each one of them:
ControlTemplate:
- you can use template-binding to bind some of the elements' properties defined in your template with the templated control's properties. Like to bind a rectangle's color in your template with the templated control's background color.
- you can use ContentPresenter to display the templated control's Content somewhere in your ControlTemplate (in case your templated control is ContentControl control).
- and you can use ItemsPresenter to display the templated control's items in case your templated control is ItemsControl control.

DataTemplate/HierarchicalDataTemplate:
- you can bind the elements you defined in your DataTemplate with properties of your corresponding Data (not control's property) classes.



Example:
if you have TreeView control and you have TreeViewItem(s) in it. The TreeViewItem is going to have some GUI in it to display the following:
- plus/minus button.
- border.
- place to display the header of the item, may be text block.
- place to display the child items of it, may be a stack.

if you use DataTemplate/HierarchicalDataTemplate, you only need to worry about displaying the text block (Content); so you don't have to worry about the plus/minus button nor to worry about the child items.

On the other hand, if you use ControlTemplate for this TreeViewItem, you will have to draw the plus/minus button and where to display the textblock (ContentPresenter) and where to display the child items (ItemsPresenter). and then you can add your own decorations around them.

I will keep updating this post as necessary. Please, let me know what you think and if you have any questions or concerns.

Wednesday, February 9, 2011

HierarchicalDataTemplate not finding the specified ItemsSource

I had problem, today. My HierarchicalDataTemplate did not find the collection specified in its ItemsSource property. Well, the collection was there but the problem was that the collection was a data member; it should be a property. Case is closed