Search code examples
silverlightsilverlight-4.0treeviewhierarchicaldatatemplate

HierarchicalDataTemplate for self referencing table


I try to implement HierarchicalDataTemplate for the self referencing table in Silverlight 4.

enter image description here

It shows all items in the TreeView like 1 level instead of the hierarchical view. It should be 3 levels of the items.

enter image description here

So I got stuck how to do it... Any clue? Thank you!

<UserControl x:Class="TreeViewCRUD.MainPage"
 xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"             
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:Crud="clr-namespace:TreeViewCRUD"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid>
           <sdk:TreeView Height="403" Margin="0,0,0,0"  Name="TreeView1" Background="Beige" >
        <sdk:TreeView.ItemTemplate>
            <sdk:HierarchicalDataTemplate ItemsSource="{Binding Divisions}" >
                <TextBlock Text="{Binding Name, Mode=OneWay}" Margin="5,0"></TextBlock>
           </sdk:HierarchicalDataTemplate>                
        </sdk:TreeView.ItemTemplate>
    </sdk:TreeView>
    </Grid>
</UserControl>

and C#

 void client_GetDivisionsCompleted(object sender, MyService.GetDivisionsCompletedEventArgs e)
        {
            var lst = e.Result;
            try
            {
                TreeView1.DataContext = lst;
                // TreeView1.ItemsSource = lst;
                TreeView1.ItemsSource =  lst.Where(a=>a.DivisionID != null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
                MessageBox.Show(ex.StackTrace.ToString());
            }
        }

Solution

  • I suspect that your XAML is correct(mostly) and the data is the issue. I assume lst contains some data like

    ID    DivisionID  Divisions1
    1     null        (List<Division>)
    2     1           (List<Division>)
    3     2           (List<Division>)
    

    When what you really need lst to be is

    ID    DivisionID  Divisions1
    1     null        (List<Division>)
    

    Now lst[0].Divisions1 would be

    ID    DivisionID  Divisions1
    2     1           (List<Division>)
    

    And finally lst[0].Divisions1[0].Divisions1 would be

    ID    DivisionID  Divisions1
    3     2           (List<Division>)
    

    Verify that the data from WCF is coming with the Navigation Properties intact. Even if lst shows all 3 elements instead just the top level one, you should be able to filter that down client side.

    The last thing I noticed is that you are using ItemsSource="{Binding Divisions}" for your binding. However, in the class diagram, the properties name is Divisions1