WPF C# Get Root Node of TreeView

2019-06-02 07:12发布

I have a TreeView that is binded through a HierarchicalDataTemplate

        <HierarchicalDataTemplate x:Key="HierachrTree" DataType="{x:Type src:Ordner}" ItemsSource="{Binding UnterOrdner}">
                <TextBlock Text="{Binding OrdnerName}"/>
    </HierarchicalDataTemplate>

Thats my TreeView:

<TreeView Name="DokumentBrowser" ItemTemplate="{StaticResource HierachrTree}"

Now I want to get the first node and set the IsExpanded Property to false.

I tried it this way

        ItemCollection ic = DokumentBrowser.Items;
        TreeViewItem tvi = (TreeViewItem)ic.GetItemAt(0);
        tvi.IsExpanded = false;

but i can't cast the Object back to a TreeViewItem to get the IsExpanded Property.

标签: c# wpf treeview
1条回答
走好不送
2楼-- · 2019-06-02 07:53

TreeView.Items is a collection of the data objects, not of the TreeViewItems. You can use the ItemContainerGenerator to get the mapping from data objects to the TreeViewItems that are the containers.

TreeViewItem tvi =
    (TreeViewItem) DokumentBrowser.ItemContainerGenerator.ContainerFromIndex(0);

If you start with a data object instead of the index then you can use ContainerFromItem:

TreeViewItem tvi =
    (TreeViewItem) DokumentBrowser.ItemContainerGenerator.ContainerFromItem(
        DokumentBrowser.Items.GetItemAt(0));
查看更多
登录 后发表回答