我目前正在WPF中编写一个文件夹浏览器对话框。为了显示树我使用TreeView:
<TreeView Name="FolderView" ItemsSource="{Binding DataTrees}" Grid.Row="0">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Tree}">
<TreeViewItem IsSelected="{Binding IsSelected, Mode=TwoWay}" IsExpanded="{Binding IsExpanded, Mode=TwoWay}" Header="{Binding Name}" HorizontalAlignment="Left"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
目前我有三个问题:
我不知道问题在哪里,所以请评论,我会更新我的问题!
编辑: Itemsource是一个List 数据树类:
public class DataTree:INotifyPropertyChanged
{
private string path;
private string name;
private ObservableCollection<DataTree> tree;
private bool isSelected;
private bool isExpanded;
}
(简单代码 - 没有Propertys和INotifyPropertyChanged的实现)
答案 0 :(得分:8)
请勿直接将TreeViewItem
添加到ItemTemplate
:
<TreeView Name="FolderView" ItemsSource="{Binding DataTrees}" Grid.Row="0">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Tree}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
与任何ItemsControl
一样,TreeView
将其数据项包装到项容器中(在您的情况下为TreeViewItem
)。因此,选择和扩展等内容应通过ItemContainerStyle
设置。