我有一个ItemsControl
,它绑定到一个集合,我指定 aHierarchicalDataTemplate
来呈现项目。我也有一个模板选择器,因为单个项目的渲染会很谨慎。由于某种原因,这不起作用。
以下是代码的摘录,您能帮忙吗?我正在寻找从以下层次结构 Parent->Child Collection->SubChildCollection 呈现项目(如下面的代码)。
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication2="clr-namespace:WpfApplication2" Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate x:Key="EntityItemTemplate" DataType="{x:Type WpfApplication2:EntityItem}">
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
<WpfApplication2:TemplateSelector x:Key="ts" EntityItemTemplate="{StaticResource EntityItemTemplate}"/>
<HierarchicalDataTemplate x:Key="hdt" DataType="{x:Type WpfApplication2:EntityGroup}" ItemsSource="{Binding Path=EntityItems}" ItemTemplateSelector="{StaticResource ts}"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ItemsControl Grid.Row="0" ItemsSource="{Binding Path=Entity.EntityGroups}" ItemTemplate="{StaticResource hdt}"></ItemsControl>
</Grid>
</Window>
public partial class MainWindow : Window
{
ViewModel vm = new ViewModel();
public MainWindow()
{
InitializeComponent();
this.DataContext = vm;
vm.Entity = new Entity()
{
Name = "abc",
EntityGroups = new ObservableCollection<EntityGroup>()
{
new EntityGroup()
{
EntityItems = new ObservableCollection<EntityItem>()
{
new EntityItem() {Name = "Entity1"},
new EntityItem() {Name = "Entity2"}
}
}
}
};
}
}
public class TemplateSelector:DataTemplateSelector
{
public DataTemplate EntityItemTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item == null || !(item is EntityItem))
return base.SelectTemplate(item, container);
return EntityItemTemplate;
}
}
public class ViewModel:NotificationObject
{
private Entity _entity;
public Entity Entity
{
get { return _entity; }
set
{
_entity = value;
RaisePropertyChanged(() => Entity);
}
}
}
public class Entity:NotificationObject
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
RaisePropertyChanged(() => Name);
}
}
private ObservableCollection<EntityGroup> _entityGroups;
public ObservableCollection<EntityGroup> EntityGroups
{
get { return _entityGroups; }
set
{
_entityGroups = value;
RaisePropertyChanged(() => EntityGroups);
}
}
}
public class EntityGroup:NotificationObject
{
public string Name { get; set; }
private ObservableCollection<EntityItem> _entityItems;
public ObservableCollection<EntityItem> EntityItems
{
get { return _entityItems; }
set
{
_entityItems = value;
RaisePropertyChanged(() => EntityItems);
}
}
}
public class EntityItem:NotificationObject
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
RaisePropertyChanged(() => Name);
}
}
}