我想在WPF中使用TreeViews可视化以下数据结构:

class MyDataContext
{
    ICollectionView Outers {get;set;}
    //...
}

class Outer
{
    string Name {get;set;}
    IEnumberable<Inner> Actions {get;set;}
}


class Inner
{
    string Description {get;set;}
    Command OnClick {get;set;}
}

到目前为止,这是我的尝试:
<!-- DataContext is MyDataContext at this  point -->
<TreeView ItemsSource="{Binding Path=Outers}">
    <TreeView.Resources>
        <DataTemplate DataType="{x:Type myns:Outer}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Path=Name}"/>

                <TreeView ItemsSource="{Binding Path=Actions}" >
                    <DataTemplate DataType="{x:Type myns:Inner}">
                        <Button Command={Binding Path=OnClick}>
                            <TextBlock Text="{Binding Path=Description}"/>
                        </Button>
                    </DataTemplate>
                </TreeView>
            </StackPanel>
        </DataTemplate>
    </TreeView.Resources>
</TreeView>

由于我收到以下InvalidOperationException,因此此访问似乎存在问题:
Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.

如果我放下内部TreeView,也没有异常(exception)(当然也没有按钮)。

最佳答案

我使用了Mateusz提到的页面(HierarchicalDataTemplate),并阅读了以下问题的答案:Bind Collection to StackPanel之后,我找到了一个解决方案,该解决方案可以满足我的要求:

在这里,球员(级别3)与团队(级别2)位于同一行:

<TreeView ItemsSource="{Binding League}">
    <!-- Conference template -->
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Teams}">
            <TextBlock Foreground="Red" Text="{Binding Name}" />
            <!-- Team template -->
            <HierarchicalDataTemplate.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Name}"/>
                        <ItemsControl ItemsSource="{Binding Players}">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <StackPanel Orientation="Horizontal">
                                    </StackPanel>
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <Button Content="{Binding }"/>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </StackPanel>
                </DataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

关于c# - 如何为WPF TreeView设置DataTemplate以显示列表的所有元素?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17741925/

10-12 00:28
查看更多