views:

161

answers:

1

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.

+2  A: 

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));
Quartermeister
Thanks! This works really good!
Mark