有关我的TreeView我有两个不同的类,提供的ItemsSource。
For my treeview I have two different classes that provide the ItemsSource.
public class TreeViewModel : ViewModelBase { public ObservableCollection<NodeViewModel> Items { get; set; } } public class NodeViewModel : ViewModelBase { public string Id { get; set; } public string Name { get; set; } public ObservableCollection<NodeViewModel> Children { get; set; } }现在我希望我的TreeView,以显示TreeViewModel的项目和显示分层数据由NodeViewModel提供。
Now I want my TreeView to display the Items in TreeViewModel and show hierarchical data as provided by the NodeViewModel.
下面是我的XAML
<Window x:Class="TreeViewMasterDetails.MainWindow" xmlns="schemas.microsoft/winfx/2006/xaml/presentation" xmlns:x="schemas.microsoft/winfx/2006/xaml" xmlns:local="clr-namespace:TreeViewMasterDetails" Title="MainWindow" Height="350" Width="525"> <Grid> <TreeView Height="Auto" HorizontalAlignment="Stretch" Margin="10" VerticalAlignment="Stretch" Width="Auto"> <TreeView.Resources> <HierarchicalDataTemplate DataType="x:Type local:TreeViewModel" ItemsSource="{Binding Items}"> <TextBlock Text="{Binding Path=Name}"></TextBlock> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="x:Type local:NodeViewModel" ItemsSource="{Binding Children}"> <TextBlock Text="{Binding Name}"></TextBlock> </HierarchicalDataTemplate> </TreeView.Resources> </TreeView> </Grid> </Window>试过提供项目为的ItemsSource 的树视图。它不显示数据分层,如果显示任何内容。
Have tried to provide Items as the ItemsSource of the TreeView. It does not show the data hierarchically, if displaying anything.
和我尝试使用的ItemTemplate 而不是 TreeView.Resources 了。
And I tried using the ItemTemplate instead of the TreeView.Resources, too.
有什么不对呢?
也许一个问题是第一个 TextBlock的文本装订?我想显示名称在项目的 NodeViewModel 属性那里。
Perhaps a problem is the first TextBlock Text Binding? I want to display the Name property of the NodeViewModel in Items there.
推荐答案作为@ sa_ddam213说,你只需要在 HierarchicalDataTemplate 为 NodeViewModel ,而是用你的code中的唯一的问题是缺少括号( {和} )为数据类型=X:类型本地:TreeViewModel在您的数据模板定义(这应该是数据类型={X:类型本地:TreeViewModel })。添加支架和的ItemsSource 结合解决了这个问题:
As @sa_ddam213 said, you only need the HierarchicalDataTemplate for NodeViewModel, but the only problem with your code was the missing braces ({ and }) for DataType="x:Type local:TreeViewModel" in your data template definitions (it should be DataType="{x:Type local:TreeViewModel}"). Adding brackets and ItemsSource binding solves the problem:
额外的 HierarchicalDataTemplate 为 TreeViewModel 不使用,但它不会伤害。
The additional HierarchicalDataTemplate for TreeViewModel is not used, but it does not harm.
更多推荐
树视图,HierarchicalDataTemplate和递归数据
发布评论