none
Bind a WPF TreeView to a composite structure (composite pattern) RRS feed

  • Question

  •  

    Hi everyone,

    I am stuck in data binding a WPF TreeView to a composite structure (composite pattern).

    The composite structure in my case looks something like this:

     

    Project (root)

    ---WorkItem 1 (leaf)

    ---WorkItem 2 (leaf)

    ---Package 1

    ------Workitem 3 (leaf)

    ------WorkItem 4 (leaf)

    ---Workitem 5

     

    The TreeView should be data bound to an project object.

     

    Has anyone managed this?

     

    Thanks!

     

    Friday, March 28, 2008 2:06 PM

Answers

All replies

  • Here is an example:

    Code Snippet

    <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <Page.Resources>
            <XmlDataProvider x:Key="tree" XPath="*">
                <x:XData>
                    <Project  xmlns="">
                        <WorkItem1/>
                        <WorkItem2/>
                        <Package1>
                            <WorkItem3/>
                            <WorkItem4/>
                        </Package1>
                        <Workitem5/>
                    </Project>
                </x:XData>
            </XmlDataProvider>
            
            <HierarchicalDataTemplate ItemsSource="{Binding XPath=child::*}" x:Key="template">
                <TextBlock Name="textBlock" Text="{Binding Name}"/>
            </HierarchicalDataTemplate>
        </Page.Resources>
        <TreeView
            ItemsSource="{Binding Source={StaticResource tree}}"
            ItemTemplate="{StaticResource template}">
            <TreeView.ItemContainerStyle>
                <Style TargetType="{x:Type TreeViewItem}">
                    <Setter Property="IsExpanded" Value="True"/>
                </Style>
            </TreeView.ItemContainerStyle>
        </TreeView>
    </Page>


    Hope this helps
    Monday, March 31, 2008 6:18 AM
  • Hi Marco Zhou,

    thanks a lot for your reply. I've found a solution by using the excelent enhanced tree created by Phillip in CodeProject:

    http://www.codeproject.com/KB/WPF/versatile_treeview.aspx

     

    Wednesday, April 2, 2008 2:19 PM