不确定这是否对您有帮助,但您可以提供自己的模板选择器,为每种类型选择不同的模板;它们都将被您选择的 ItemsPanelTemplate 对象封装,但它允许您对您指定的任何类型拥有非常不同的控件。这是我的用例,但我想您可以将相同的想法应用于 TreeView
<ItemsControl>
<ItemsControl.Resources>
<DataTemplate x:Key="templateFoo">
</DataTemplate>
<DataTemplate x:Key="templateBar">
</DataTemplate>
<DataTemplate x:Key="templateJoe">
</DataTemplate>
</ItemsControl.Resources>
<ItemsControl.ItemTemplateSelector>
<local:MyTemplateSelector></local:MyTemplateSelector>
</ItemsControl.ItemTemplateSelector>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Grid.Row"
Value="{Binding Row}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
而这在某处
public class MyTemplateSelector: DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
FrameworkElement element = container as FrameworkElement;
if (element == null || item == null)
return null;
if(item is Foo)
{
return element.FindResource("templateFoo") as DataTemplate;
}
if (item is Bar)
{
return element.FindResource("templateBar") as DataTemplate;
}
if (item is Joe)
{
return element.FindResource("templateJeo") as DataTemplate;
}
return null;
}
}