2
votes

I have a class SceneNode which contains a ObservableCollection. I want the entire tree to show up, however I can't seem to get this to work with databinding. Everything works perfectly if I just add the root to the trees items.

class SceneNode
{
    public string Name {get;set;}
    public ObserveableCollection<SceneNode> ChildrenNodes{get;set;}
    ....
}
class Scene
{
    public SceneNode Nodes{get;set;}
}

So I bind the Scene to the Trees data context and the following is my trees xaml

<TreeView MinHeight="250" ItemsSource={Binding Path=Nodes} >
    <TreeView.ItemTemplate>
                <HierarchicalDataTemplate DataType="{x:Type local:SceneNode}" ItemsSource="{Binding Path=ChildSceneNodes, UpdateSourceTrigger=PropertyChanged}">
                    <TextBlock Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}" Margin="0,10,0,10" />
                </HierarchicalDataTemplate>                
            </TreeView.ItemTemplate>
</TreeView> 

Behind the scenes I before the control with the tree is shown I bind its data context

sceneTree.Tree.DataContext = theScene;

Nothing shows, however if instead of binding the data I do

sceneTree.Tree.Items.Add( theScene.Nodes );

The tree will show and I can add and remove nodes and this activity reflects in the TreeView.

1
To solve this I made a new property in the Scene object that just returns a new ObservableCollection.Neal Cynkus

1 Answers

0
votes

The problem here is that the ItemsSource property recive a Collection and you are making the binding to a SceneNode, that is not a collection. This problem will be solved making the binding to the ChildrenNodes property:

    <TreeView x:Name="treeView" MinHeight="250" ItemsSource="{Binding Nodes.ChildrenNodes}" >
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate DataType="{x:Type WpfBackgroundWorkerQuestion:SceneNode}" ItemsSource="{Binding Path=ChildrenNodes, UpdateSourceTrigger=PropertyChanged}">
                <TextBlock Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}" Margin="0,10,0,10" />
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>