Search code examples
c#wpfxamlrecursionwindows-store-apps

How to have recursion, or a hierarchy lists and sublists in XAML?


Say I have the following class, Employee

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ObservableCollection<Employee> Underlings { get; set; }
}

And then I have the following XAML, bound to an ObservableCollection<Employee> MyEmployees

<ListBox ItemsSource="{Binding Path=MyEmployees}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Grid Tag="{Binding Path=Employee.Id}">
        <TextBlock Text="{Binding Path=Employee.Name}"></TextBlock>

        <!-- Here's where I declare my underlings -->
        <ListBox ItemsSource="{Binding Path=Employee.Underlings}">
          <ListBox.ItemTemplate>
            <DataTemplate>
              <Grid Tag="{Binding Path=Employee.Id}">
                <TextBlock Text="{Binding Path=Employee.Name}"></TextBlock>
              </Grid>
            </DataTemplate>
          </ListBox.ItemTemplate>
        </ListBox>

      </Grid>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

This allows each employee in the collection MyEmployees to have some underlings. But those underlings are also of type employee, and could have their own underlings. How do I cater for those additional levels without making my XAML very complex?

Is there some way to declare my DataTemplate separately and allow it to be referenced within itself?

Do I have to do all this from code-behind instead?

(I realise the XAML above may not be 100% correct, its just an example)


Solution

  • therefore you have to use a TreeView and not a ListBox. And You have to specify a HierarchicalDataTemplate.