AwkwardCoder
AwkwardCoder

Reputation: 25631

Expanding tree view items in WPF TreeView

I'm trying to expand the first two items in a tree view control in WPF. The tree view is bound to a collection using the MVVM pattern and I'm trying to expand the tree view for the first item and it's sub-item when ever the tree view bound collection changes.

In the following code 'secondTreeViewItem' is always null, any ideas why?

var firstAssembly = (Assembly)assemblyTree.Items[0];
var firstTreeViewItem = (TreeViewItem)assemblyTree.ItemContainerGenerator.ContainerFromItem(firstAssembly);
firstTreeViewItem.IsExpanded = true;

var secondAssembly = (Assembly)firstTreeViewItem.Items[0];
var secondTreeViewItem = (TreeViewItem)firstTreeViewItem.ItemContainerGenerator.ContainerFromItem(secondAssembly);

Upvotes: 0

Views: 420

Answers (1)

brunnerh
brunnerh

Reputation: 184386

Bind the TreeViewItem.IsExpanded property to a property on your VM in the ItemConainerStyle of the TreeView (you should pretty much never need to use the ItemContainerGenerator). Then you just need to change the property on the two targeted items.

The second item is probably null because of virtualization, you need to wait for the expansion of the first item only then will the inner items be generated.

Upvotes: 1

Related Questions