Search code examples
c#wpftreeview

WPF TreeView for a single list


How do I structure the xaml for a TreeView so that the output looks like this:

  • Permanent
    • Teachers
      • Teacher 1 Name, Teacher 1 Parking Place number
      • Teacher 2 Name, Teacher 2 Parking Place number
    • Assistants
      • Assistant 1 Name, Assistant 1 Room
      • Assistant 2 Name, Assistant 2 Room
    • Buildings
      • Building 1 Name, Building 1 Room Count
      • Building 2 Name, Building 2 Room Count.
  • Temporary
    • Teachers
      • Teacher 3 Name, Teacher 3 Parking Place number
      • Teacher 4 Name, Teacher 4 Parking Place number
    • Assistants
      • Assistant 3 Name, Assistant 3 Room
      • Assistant 4 Name, Assistant 4 Room
    • Buildings
      • Building 3 Name, Building 3 Room Count
      • Building 4 Name, Building 4 Room Count.

Classes

public class SchoolData
{
    public Contract Permanent { get; set; }
    public Contract Temporary { get; set; }
}

public class Contract
{
    public ObservableCollection<Teacher> Teachers { get; set; }
    public ObservableCollection<Assistant> Assistants { get; set; }
    public ObservableCollection<Building> Buildings { get; set; }
}

public class Teacher
{
    public string Name { get; set; }
    public int ParkingPlaceNumber { get; set; }
}

public class Assistant
{
    public string Name { get; set; }
    public int RoomNumber { get; set; } 
}

public class Building
{
    public string Name { get; set; }
    public int NumberOfRooms { get; set; } 
}

I think I need 6 separate TreeViews for each of the six lists that I want to display. I have tried the following, but all I get are object names and I do not get headers or heirarchical views.

<TreeView ItemsSource="{Binding SchoolData.Permanent.Teachers}" />
<TreeView ItemsSource="{Binding SchoolData.Permanent.Assistants}" />
<TreeView ItemsSource="{Binding SchoolData.Permanent.Buildings}" />
<TreeView ItemsSource="{Binding SchoolData.Temporary.Teachers}" />
<TreeView ItemsSource="{Binding SchoolData.Temporary.Assistants}" />
<TreeView ItemsSource="{Binding SchoolData.Temporary.Buildings}" />

What should the xaml look like to achieve the needed tree view?


Solution

  • <TreeView>
        <TreeViewItem Header="Permanent" IsExpanded="True">
            <TreeViewItem Header="Teachers" ItemsSource="{Binding SchoolData.Permanent.Teachers}"/>
            <TreeViewItem Header="Buildings" ItemsSource="{Binding SchoolData.Permanent.Buildings}"/> 
        </TreeViewItem>
    
        <TreeViewItem Header="Temporary" IsExpanded="True">
            <TreeViewItem Header="Teachers" ItemsSource="{Binding SchoolData.Temporary.Teachers}"/>
            <TreeViewItem Header="Buildings" ItemsSource="{Binding SchoolData.Temporary.Buildings}"/> 
        </TreeViewItem>
    </TreeView>