I have a MVVM WPF application with a tree containing self referenced data, this data is bound to the tree with a hierarchical converter. (As in example: http://www.telerik.com/h
If your ItemsSource
is made up of different Types, then you can simply create HierarchicalDataTemplates
and not assign an x:Key. If there is no x:Key attribute for a DataTemplate
, the framework will use this DataTemplate
when it comes across the type and tries to visually display it (you can read more about implicit DataTemplates
here). For example, if you have a type Circle and another type Square, you would have the following templates in your Resources:
Then if your TreeView
encounters one of these Types in its ItemsSource
, it will use the HierarchicalDataTemplate
for that specific type.
You can read more about HierarchicalDataTemplates
here, and this link has an example of how they are used in a TreeView
.
OR
If your items are all the same Type, and only differentiated by a property (such as Type), you'll need to use a DataTemplateSelector
. Here is a simple example of one:
codebehind:
public class ShapeTemplateSelector : DataTemplateSelector
{
public DataTemplate CircleTemplate { get; set; }
public DataTemplate SquareTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
Shape shape = item as Shape;
if (shape != null)
{
if (shape.Type == "Circle")
return this.CircleTemplate;
else if (shape.Type == "Square")
return this.SquareTemplate;
}
return null;
}
}
And XAML:
Then in your TreeView
, you simply assign the selector