3

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)

4

2 回答 2

0

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

于 2013-08-19T09:41:54.937 回答
0

You could define the DataTemplate inside the ListBoxes Resources as the default template for Employees:

<ListBox ItemsSource="{Binding MyEmployees}">
    <ListBox.Resources>
        <DataTemplate DataType="{x:Type myns:Employee}">
            <Grid Tag="{Binding Id}">
                <TextBlock Text="{Binding Name}"></TextBlock>
                <ListBox ItemsSource="{Binding Underlings}" />
            </Grid>
        </DataTemplate>
    </ListBox.Resources>
</ListBox>
于 2013-08-19T10:52:24.827 回答