如何创建像这样的树视图:
<TreeViewItem Header="Customers" ItemsSource="{Binding Customers}">
我想创建像这样的子项目模板
<TreeViewItem Header="{Binding Header}">
<TreeViewItem Header="Delete"/>
<TreeViewItem Header="Open"/>
</TreeViewItem>
但它并没有那么好用,因为我最终使用了datatemplate treeviewitem的treeviewitem,但是我想覆盖子元素的controltemplate,但不是父元素。 当然,我想避免我的绑定是TreeViewItem,也不想用那些静态obejct“打开”,“删除”创建子项。
答案 0 :(得分:3)
Here是我读过的关于TreeView
的最佳文章之一。
如果“删除”和“打开”命令是某些集合的项目,则可以在TreeView.Resources
内部声明多个具有不同DataType
的DataTemplates。 (命令的TargetType是ICommand)。
但似乎你根本不需要TreeView。 客户是列表的标题。如果您希望它是epxpandable,请使用Expander控件 然后,为每个客户提供一个数据模板就足够了。
<DataTemplate DataType="CustomerTypeName">
<Expander Header="{Binding CustomerName}">
<Button Command="{Binding DeleteCustomerCmd}" Content="Delete" Margin="15,0,0,0"/>
<Button Command="{Binding OpenCustomerCmd}" Content="Open" Margin="15,0,0,0"/>
<Expander/>
<DataTemplate>
但是在这里你会遇到一些选择亮点的麻烦。
public class CommandWrapper
{
ICommand Command {get;set;}
string CommandName {get;set;}
}
public class CustomerViewModel
{
Customer Customer {get;set;}
IEnumerable<CommandWrapper> Commands {get;}
}
让客户成为CustomerViewModel
的集合。
然后以下XAML可以提供帮助:
<TreeView ItemsSource="{Binding ...}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="TypeHoldingCustomersCollection"
ItemsSource="{Binding Customers}">
<TextBlock Text="Customers"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="CustomerViewModel"
ItemsSource="{Binding Commands}">
<TextBlock Text="{Binding Path=Customer.Name}"/>
</HierarchicalDataTemplate>
<DataTemplate DataType="CommandWrapper">
<Button Content="{Binding CommandName}" Command="{Binding Command}"/>
</DataTemplate>
</TreeView.Resources>
</TreeView>
答案 1 :(得分:0)
您将需要使用HierarchicalDataTemplate。