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.
使用WPF,我有一个TreeView控件,我想通过过程代码动态设置它的ItemTemplate。我该怎么做呢?我假设我需要在某个地方找到资源。
myTreeViewControl.ItemTemplate = ??
2 个解决方案
#1
11
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.
如果它在你的应用程序的其他地方,我认为App.FindResource(“SomeTemplate”)将工作。
#2
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.
如果您的treeview控件需要不同的项目模板,则应实现DataTemplateSelector类并将其实例设置为树视图。据我所知,DataTemplateSelector有一个属性。
#1
11
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.
如果它在你的应用程序的其他地方,我认为App.FindResource(“SomeTemplate”)将工作。
#2
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.
如果您的treeview控件需要不同的项目模板,则应实现DataTemplateSelector类并将其实例设置为树视图。据我所知,DataTemplateSelector有一个属性。