2

I am looking for a way to make my TreeView display items in Canvas panel.

<TreeView>
    <TreeView.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas IsItemsHost="True"/>
        </ItemsPanelTemplate>
    </TreeView.ItemsPanel>
    <TreeViewItem Header="Root" IsExpanded="True" Canvas.Left="50" Canvas.Top="20">
        <TreeViewItem Header="Alpha" Canvas.Left="10" Canvas.Top="50">
            <TreeViewItem Header="Sub"/>
        </TreeViewItem>
        <TreeViewItem Header="Beta"/>
        <TreeViewItem Header="Gamma"/>
    </TreeViewItem>
</TreeView>

This solution allows me to move around Root TreeViewItem, but I want every single item in TreeView to respect Canvas attached properties. What I mean is, when Root {Left = 50, Top = 10} (to here it works) contains Alpha {Left = 0, Top=0}, Root would be at [50,10] and Alpha at [0,0] (coordinates are absolute to Canvas).

The reason why only Root TreeViewItem places itself correctly is, that I use TreeView.ItemsPanel. I have a feeling I should use TreeView.ItemContainerStyle instead, but I really don't know how.

Any help is appreciated of course, preferably incorporating HierarchicalDataTemplate too so _I know how to connect the solution with Binding.

animuson
  • 53,861
  • 28
  • 137
  • 147
Aaron Summernite
  • 355
  • 1
  • 5
  • 15
  • Is there any particular reason you're using a `TreeView` instead of an `ItemsControl`? – Rachel Feb 29 '12 at 20:04
  • Yes, I want to use `HierarchicalDataTemplate` and from what I've found on the Internet, it's only working with `TreeView`. But I will go with `ItemsControl` gladly if there is a way to make this work with it. – Aaron Summernite Feb 29 '12 at 20:26
  • Are the Data Objects in your TreeView all of the same type? If they are, you could use an Implicit `DataTemplate` instead of a `HierarchicalDataTemplate`. – Rachel Feb 29 '12 at 20:28
  • Well TreeView is binded to `XDocument` and uses `HierarchicalDataTemplate` so I get all the levels of document displayed. Data are hierarchical. – Aaron Summernite Feb 29 '12 at 20:30
  • @Rachel: I think you are drawing the wrong conclusion here, it should be: If so you can apply the template via the `TreeView.ItemTemplate` otherwise it needs to be applied implicitly. In any case it needs to be a hierarchical datatemplate to support children. – H.B. Feb 29 '12 at 23:59

1 Answers1

4

TreeViewItems lay out their own children, they each have their own panel, so you need to change the canvas on the TreeView and the items. To do this apply a style which changes the panel, either implicitly via resources or the ItemContainerStyle.

<Style TargetType="TreeViewItem">
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <TreeViewItem.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas />
                </ItemsPanelTemplate>
            </TreeViewItem.ItemsPanel>
        </Setter.Value>
    </Setter>
</Style>
H.B.
  • 166,899
  • 29
  • 327
  • 400