WPF TreeView 分层绑定。
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12532435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF TreeView hierarchical binding.
提问by Baranovskiy Dmitry
just starting with wpf. I need to bind the object (Hierarchical) Folder
刚从 wpf 开始。我需要绑定对象(分层)文件夹
public class Folder
{
public Folder()
{
this.Name = string.Empty;
this.Modules = new ObservableCollection<Module>();
this.Folders = new List<Folder>();
this.HasChild = false;
}
public Folder(Folder parent)
{
this.Name = string.Empty;
this.Modules = new ObservableCollection<Module>();
this.Folders = new List<Folder>();
this.HasChild = false;
this.Parent = parent;
}
public bool HasChild { get; set; }
public string Name { get; set; }
public List<Folder> Folders { get; set; }
public ObservableCollection<Module> Modules { get; set; }
public Folder Parent { get; set; }
public Folder IfItemExists(string name)
{
foreach (Folder folder in Folders)
{
if (folder.Name == name)
{
return folder;
}
}
return null;
}
}
to the treeview. I am doing like that
到树视图。我这样做
<TreeView Name="treeView" Margin="5">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Folders}" DataType="{x:Type ModulesUpToDateChecker:Folder}">
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}"></TextBlock>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
and have just empty docpanel. The object is filled write. Eche child has own child with the same Type.
并且只有空的 docpanel。对象被填充写入。Eche child 有自己的相同 Type 的 child。
采纳答案by SvenG
A HierarchicalDataTemplate is already a DataTemplate (it derives from it). So just skip the ItemTemplate and DataTemplate stuff inside your HierarchicalDataTemplate like so:
HierarchicalDataTemplate 已经是一个 DataTemplate(它派生自它)。因此,只需跳过 HierarchicalDataTemplate 中的 ItemTemplate 和 DataTemplate 内容,如下所示:
<TreeView Name="treeView" Margin="5">
<TreeView.Resources>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Folders}" DataType="{x:Type WpfApplication220:Folder}">
<TextBlock Text="{Binding Path=Name}"></TextBlock>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
Oh and you have to set the ItemsSource of your treeview either programmatically or in your markup ..
哦,您必须以编程方式或在标记中设置树视图的 ItemsSource ..
treeView.ItemsSource = ..yourFolderList..
回答by Raúl Ota?o
Try to do this:
尝试这样做:
<TreeView Name="treeView" Margin="5">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Folders}" DataType="x:Type ModulesUpToDateChecker:Folder}">
<Grid>
<TextBlock Text="{Binding Path=Name}"></TextBlock>
</Grid>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>

