我已经绕了好几天车轴了。
我想要做的是创建一个UserControl,其中包含一个TreeView。TreeView应该显示有关Show的信息,而Show中有一个Instructions列表,等等……
我试过用不同的方式来做这件事,但是我无法让数据显示。下面是我尝试过的一些代码片段:
<TreeView ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}, Path=DataContext.Show}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Instructions}">
<TextBlock Text="{Binding Path=ShowName}"/>
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Sounds}">
<TextBlock Text="{Binding Path=Name}"/>
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Nodes}">
<TextBlock Text="{Binding Path=Name}"/>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>我也试过..。
<DockPanel>
<DockPanel.Resources>
<HierarchicalDataTemplate DataType="{x:Type show:Show}" ItemsSource="{Binding Path=Instructions}">
<TextBlock Text="{Binding Path=ShowName}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type show:Instruction}" ItemsSource="{Binding Path=Sounds}">
<TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type show:SoundInstruction}" ItemsSource="{Binding Path=Nodes}">
<TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type show:NodeInstruction}">
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
</DockPanel.Resources>
<TreeView ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}, Path=DataContext.Show}">
</TreeView>
</DockPanel>但似乎什么都起不到作用。在我的MainWindow中,我有这样的代码来初始化数据上下文:
Show s = new Show("Hamlet");
s.AddInstruction(new Instruction("Inst1"));
s.AddInstruction(new Instruction("Inst2"));
ShowViewModel vm = new ShowViewModel(s);
DataContext = vm;如果在这件事上有任何帮助,我们将不胜感激。
杰克
发布于 2014-05-29 05:19:16
您的ItemsSource必须绑定到IEnumerable。从您的代码来看,您的ShowViewModel.Show似乎是一个类型为Show的属性,它是一个单独的对象。这是行不通的,你必须把它变成一个集合(最好是ObservableCollection)。
第二种定义模板的方法(并排的,而不是嵌套的)肯定更好。
此外,假设您不将DataContext设置为Window和DockPanel之间的任何其他内容,则可以更改以下内容:
<TreeView ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}, Path=DataContext.Show}">对此:
<TreeView ItemsSource="{Binding Show}">您的数据上下文将自动从可视树继承下来。
https://stackoverflow.com/questions/23923821
复制相似问题