简体   繁体   中英

WPF MVVM TreeView Groups

I have 3 class's:

  1. Building
  2. Office
  3. Person

In a Building there are offices and in each office there are persons. My ViewModel have a ObservableCollection of Offices and one of the properties is the Building and ObservableCollection.

What is the best way to create TreeView that is binded to office and it group by Building, Offices, persons?

Example:

  • Building1

    • Office1
      • Person1
      • Person2
      • Person3
    • Office2
      • Person4
      • person5
  • Building2

    • Office3
      • Person6
      • Person7
      • Person8
    • Office4
      • Person9
      • person10

If you want to get this layout in your treeview you will be creating HieratchicalDataTemplates for Buildings and Offices and a DataTemplate for a Person. I am assumijng that you have a text property called Name in all 3 of your ViewModels.

<TreeView ItemsSource="{Binding Buildings}">
            <TreeView.Resources>
                <HierarchicalDataTemplate ItemsSource="{Binding Offices}" DataType="{x:Type VM:BuildingViewModel}">
                    <TextBlock Text="{Binding Name}"/>
                </HierarchicalDataTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Persons}" DataType="{x:Type VM:OfficeViewModel}">
                    <TextBlock Text="{Binding Name}"/>
                </HierarchicalDataTemplate>
                <DataTemplate DataType="{x:Type VM:PersonViewModel}">
                    <TextBlock Text="{Binding Name}"/>
                </DataTemplate>
            </TreeView.Resources>
        </TreeView>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM