views:

2968

answers:

4

Is there a way to only load child nodes when the parent node is expanded? The problem that I’m running into is that the “expand” icon doesn’t show up if a node doesn’t have any children. Since I don’t want to load the children until the icon is clicked, I’m left with a bit of a catch 22.

+1  A: 

With tree views you usually have to load the children of each displayed node.

So if you only display the root you need to load the roots children too. Once you expand the root you need to load the children of each child if you want the expand stuff for those children.

Brody
A: 

i was also looking at this. I think you need to write your own subclass of the TreeNode that loads the child nodes on demand.
One approach I used in a windows forms TreeView was to add an empty child node to each node and then remove this when the node was expanded and the real child nodes were needed. The problem with this approach is that you get false expandable nodes, but if you can live with it then its a simple solution.

Rune Grimstad
+1  A: 

It is perfectly possible to have tree controls load the child nodes on demand, and you can do this with the Silverlight TreeView. When you populate the root nodes if the data for this is coming from a database for example then for each node also return whether it has children or not, if it does then add one dummy child, this will make the control put a + next to it. Handle the expanded event and in this see if the child is the dummy node, if it is remove it, get the children from the database and add them.

+2  A: 

First, read this post: http://bea.stollnitz.com/blog/?p=55

Second, inherit TreeViewItem and TreeView:

public class TreeViewItemEx : TreeViewItem {
 protected override DependencyObject GetContainerForItemOverride() {
  TreeViewItemEx tvi = new TreeViewItemEx();
  Binding expandedBinding = new Binding("IsExpanded");
  expandedBinding.Mode = BindingMode.TwoWay;
  tvi.SetBinding(TreeViewItemEx.IsExpandedProperty, expandedBinding);
  return tvi;
 }
}

public class TreeViewEx : TreeView {
 protected override DependencyObject GetContainerForItemOverride() {
  TreeViewItemEx tvi = new TreeViewItemEx();
  Binding expandedBinding = new Binding("IsExpanded");
  expandedBinding.Mode = BindingMode.TwoWay;
  tvi.SetBinding(TreeViewItemEx.IsExpandedProperty, expandedBinding);

  return tvi;
 }
}

Third, binding your Model's property to "IsExpanded".

Homer