Silverlight TreeView - Load data when node is expanded

herbrandson picture herbrandson · Nov 21, 2008 · Viewed 7.2k times · Source

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.

Answer

Homer picture Homer · Oct 8, 2009

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".