How do I set ItemTemplate dynamically in WPF?
Asked Answered
B

2

9

Using WPF, I have a TreeView control that I want to set its ItemTemplate dynamically through procedural code. How do I do this? I assume I need to find the resource somewhere.

myTreeViewControl.ItemTemplate =   ??
Bosk answered 27/8, 2008 at 20:48 Comment(0)
B
12

If the template is defined in your <Window.Resources> section directly:

myTreeViewControl.ItemTemplate = this.Resources["SomeTemplate"] as DataTemplate;

If it's somewhere deep within your window, like in a <Grid.Resources> section or something, I think this'll work:

myTreeViewControl.ItemTemplate = this.FindResource("SomeTemplate") as DataTemplate;

And if it's elsewhere in your application, I think App.FindResource("SomeTemplate") will work.

Binky answered 27/8, 2008 at 20:51 Comment(0)
A
2

if your treeview control requires different templates for your items, you should implement DataTemplateSelector class and set it's instance to your tree view. as far as i remember there is a property of DataTemplateSelector.

Arin answered 16/9, 2008 at 4:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.