Convert a HierarchicalDataTemplate to TreeViewItem

How do I get a TreeViewItem from a HierarchicalDataTemplate?

XAML:

<HierarchicalDataTemplateDataType ="{x:Type src:League}"

ItemsSource ="{Binding Path=Divisions}">

<TextBlockText="{Binding Path=Name}"/>

</HierarchicalDataTemplate>

<HierarchicalDataTemplateDataType ="{x:Type srcBig Smileivision}"

ItemsSource ="{Binding Path=Teams}">

<TextBlockText="{Binding Path=Name}"/>

</HierarchicalDataTemplate>

<DataTemplateDataType="{x:Type src:Team}">

<TextBlockText="{Binding Path=Name}"/>

</DataTemplate>

Code:

void ExpandItems(TreeViewItem item)

{

item.IsExpanded =true;

for (int i = 0; i < item.Items.Count; i++)

{

TreeViewItem it = item.ItemsIdeaasTreeViewItem;

if (it !=null) //***it is null because the item is a Division object, how do I get the TreeViewItem?

ExpandItems(it);

}

}

[4462 byte] By [Anthony_Sebastian] at [2008-1-8]
# 1
TreeViewItem it = (TreeViewItem)(item.ItemContainerGenerator.ContainerFromIndex(i));
Yi-LunLuo-MSFT at 2007-10-2 > top of Msdn Tech,Visual Studio Orcas,Windows Presentation Foundation (WPF)...
# 2

Thank you pointing me in the right direction. I should have posted my objective which is to expand nodes when the tree is loaded, before the user sees it. Because the generator is not started until the node is expanded I had to hookup the generator status changed event on each root tvi, expand the root tvi, wait for the generator to finish, then get the child tvi's from the finished root tvi and re-iterate. Below is an example of expanding all nodes:

Code Snippet

Contructor()

{

//Init...

this.tree.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);

}

void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)

{

ItemContainerGenerator gen = sender as ItemContainerGenerator;

if (gen.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)

{

int i = 0;

TreeViewItem tvi = (TreeViewItem)gen.ContainerFromIndex(i++);

while (tvi != null)

{

tvi.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);

tvi.IsExpanded = true;

tvi = (TreeViewItem)gen.ContainerFromIndex(i++);

}

}

}

Anthony_Sebastian at 2007-10-2 > top of Msdn Tech,Visual Studio Orcas,Windows Presentation Foundation (WPF)...
# 3

You can expand all nodes in a TreeView more simply in the XAML. Add the following to the TreeView declaration:

Code Snippet

<TreeView.Resources>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="True" />
</Style>
</TreeView.Resources>

GrahamP at 2007-10-2 > top of Msdn Tech,Visual Studio Orcas,Windows Presentation Foundation (WPF)...
# 4
Nice! Thanks.
Anthony_Sebastian at 2007-10-2 > top of Msdn Tech,Visual Studio Orcas,Windows Presentation Foundation (WPF)...

Visual Studio Orcas

Site Classified