You seem to be a little bit confused by the different Template
s that WPF provides. First, we can define a Style
for the TreeViewItem
(the ItemContainerStyle
), the data item 'container'. Then we can define a DataTemplate
for the data item that appears within the container (the ItemTemplate
), or HierarchicalDataTemplate
in your case.
So don't try to put your data item Binding
in the ItemContainerStyle
and don't put your UI element Binding
in the DataTemplate
and you should be fine. Note that you can supply one DataTemplate
/HierarchicalDataTemplate
without setting their x:Key
property for each data type in your collection and there is no need to use a DataTemplateSelector
... let WPF do the implicit selecting of DataTemplate
s based on the data item's types. Here is a simple example:
In code:
public class BaseClass { }
public class ClassA : BaseClass { }
public class ClassB : BaseClass { }
...
public Observablecollection<BaseClass> Items { get ; set; }
In XAML:
<ListBox ItemsSource="{Binding Items}">
<ListBox.Resources>
<DataTemplate DataType="{x:Type DataTypes:ClassA}">
<Ellipse Fill="Red" />
</DataTemplate>
<DataTemplate DataType="{x:Type DataTypes:ClassB}">
<Rectangle Fill="Blue" />
</DataTemplate>
</ListBox.Resources>
</ListBox>
This ListBox
would display red circles for the ClassA
items and blue rectangles for the ClassB
items. You can do a similar thing for your folders and files