Reputation: 61
I have a TreeView
and manually add two items (TreeViewItem
) to it.
And I want to apply ItemTemplate
to those two items but it seems like the ItemTemplate
is not applied to them. Actually I have deeper levels in the tree (so item1 and item2 each has a collection as ItemsSource
, and there are more HierarchicalDataTemplates
for them). But to demonstrate the first Template NOT being applied to the first-level items, I simplified the example. Below are the behind codes.
TreeViewItem item1 = new TreeViewItem();
TreeViewItem item2 = new TreeViewItem();
trvRecordList.Items.Add(item1);
trvRecordList.Items.Add(item2);
And here are my xaml codes. The HierarchicalDataTemplate
is written in a correct place.
<HierarchicalDataTemplate x:Key="My_Template">
<StackPanel Orientation="Horizontal">
<Image Source="Images/Star_Blue.png"
Margin="0,0,4,0" Height="16" Width="16"/>
<TextBox Text="abcd"/>
</StackPanel>
</HierarchicalDataTemplate>
<TreeView Name="trvRecordList" Margin="2"
ItemTemplate="{StaticResource My_Template}">
</TreeView>
Upvotes: 1
Views: 1953
Reputation: 4109
Since you are adding a list of TreeViewItem
objects to your TreeView
, My_Template will not be applied to it. If you check your output window, you would be getting an error as shown below
System.Windows.Data Error: 26 : ItemTemplate and ItemTemplateSelector are ignored for items already of the ItemsControl's container type; Type='TreeViewItem'
The solution is to apply My_Template to the ItemTemplate
property of the TreeViewItem
itself.
Below are the modifications I've done to your code
TreeViewItem item1 = new TreeViewItem();
TreeViewItem item2 = new TreeViewItem();
item1.Items.Add("");
item1.Items.Add("");
item1.ItemTemplate = FindResource("My_Template") as HierarchicalDataTemplate;
item2.Items.Add("");
item2.Items.Add("");
item2.ItemTemplate = FindResource("My_Template") as HierarchicalDataTemplate;
trvRecordList.Items.Add(item1);
trvRecordList.Items.Add(item2);
Go through the below link to learn more about HierarchicalDataTemplate
Edit:
If you want to apply My_Template to the TreeView
then try this code.
trvRecordList.Items.Add("");
trvRecordList.Items.Add("");
Upvotes: 1
Reputation: 1266
The ItemTemplate
is for data objects. Check the remarks for ItemTemplate on MSDN.
TreeViewItem
is container generated for each data item and is styled thru ItemContainerTemplate
. ItemContainerTemplate on MSDN
Upvotes: 0