如何将ObservableCollection绑定到TreeView(分层)

时间:2015-02-05 20:40:33

标签: c# .net wpf xaml treeview

我有以下TreeView:

<Grid>
    <TreeView Background="LightGoldenrodYellow"  Grid.Row="3">

        <TreeViewItem Header="Section 4">
            <TreeViewItem>
                <TreeViewItem.Header>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="Total:"  Width="150"/>
                        <TextBlock Text="{Binding Pool.Count}" />
                    </StackPanel>
                </TreeViewItem.Header>
            </TreeViewItem>
            <TreeViewItem>
                <TreeViewItem.Header>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="Code" Width="150" />
                        <TextBlock Text="{Binding SecretViewModel.Codes}" />
                    </StackPanel>
                </TreeViewItem.Header>
            </TreeViewItem>
            <TreeViewItem Header="Sub-Section 4.1">
                <TreeViewItem>
                    <ListBox  ItemsSource="{Binding Path=ListOfNames, UpdateSourceTrigger=PropertyChanged}" />
                </TreeViewItem>
            </TreeViewItem>
        </TreeViewItem>

        <TreeViewItem Header="Section 5">
            <TreeViewItem>
                <TreeViewItem.Header>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="Color:" Width="150" />
                        <TextBlock Text="{Binding Colors}" />
                    </StackPanel>
                </TreeViewItem.Header>
            </TreeViewItem>

    </TreeView>
</Grid>

如何替换Listbox并将ObservableCollection绑定到TreeviewItem?它看起来应该是分层

我试图插入此代码而不是使用TextBox,但这不起作用:

<HierarchicalDataTemplate>
    <HierarchicalDataTemplate.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=ListOfNames, UpdateSourceTrigger=PropertyChanged}"/>
        </DataTemplate>
    </HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>

1 个答案:

答案 0 :(得分:1)

不太确定你到底要做的是什么。你的意思不是......

<TreeViewItem Header="Section 4">
    <TreeViewItem Header="Sub-Section 4.1" 
                  ItemsSource="{Binding Path=ListOfNames,
                                UpdateSourceTrigger=PropertyChanged}" />
</TreeViewItem>

enter image description here