views:

89

answers:

1

I know that there has already been some discussion about this, but I haven't been able to solve my problem yet.

As for loading items on demand that works fine already. I have subclassed TreeViewItem, and whenever the 'Expanded' event is fired, my TreeViewItemSource fetches the next few Nodes.

But this is a but messy, as I have the custom TreeViewItem, and, because I add items via TreeView.Items.Add(), I lose the ability to define the representation of my nodes in XAML.

This is somewhat inconvinient as I want to display an icon with each node, and putting that into code is at least a little against the rules.

So what my question boils down to: Isn't it possible to bind to the IsExpanded property without the "trick" from Bea Stollnitz?

This is how I supposed it would work, but it doesn't:

  <sdk:TreeView Name="treeView1">
    <Style TargetType="sdk:TreeViewItem">                    
      <Setter Property="IsExpanded" Value="{Binding IsExpanded}" />
    </Style>
    <sdk:TreeView.ItemTemplate>
      <sdk:HierarchicalDataTemplate ItemsSource="{Binding Children}" >
        <TextBlock Text="{Binding Path=Label, Mode=OneWay}" />
      </sdk:HierarchicalDataTemplate>
    </sdk:TreeView.ItemTemplate>
  </sdk:TreeView>

So if I could bind to IsExpanded I could fetch new Nodes whenever the parent is expanded.

What am I doing wrong? Wouldn't this be the best solution for the problem? Any new ideas?

Just to be clear: The ideal scenario would be, that I could grab bunch of POCOs (holding for example the Label and the Icon) from a webservice and do all the styling via XAML. Preferably I wouldn't have to box them into something else, as this is very slow (at least in my current implementation, about 1000 items, scrolling fells really bad).

Thanks in advance.

A: 

One way to do it would be to write an attached behavior that listens for the Expanded event and loads the data then. This way you aren't subclassing TreeViewItem and still would write all your layout in XAML, but you can still get the dynamic load behavior you desire.

Edit

Something like this (likely doesn't compile but should give you an idea)

public class LoadDynamicBehavior : Behavior<TreeViewItem>
{
    protected override void OnAttached()
    {
        AssociatedObject.Expanded += LoadData;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.Expanded -= LoadData;
    }

    private void LoadData(object sender, EventArgs e)
    {
        // Load the correct data here and push it into AssociatedObject
    }
}
Stephan
How can I catch the Expanded event?Would you be so generous and provide maybe a snippet or a little more explanation?
Michael
Added code to show.
Stephan