简体   繁体   中英

WPF: Add multiple level with different types items to TreeView

I have a class (ClassA) that contains two different types of lists, List of ClassBTypes and List of ClassC . ClassBTypes has its own List of ClassB .

I want to achieve the below structure for the TreeView

-- ClassAName   
-- -- ClassBType1Name  
-- -- -- ClassB1Name  
-- -- -- ClassB2Name     
-- -- ClassBType2Name  
-- -- -- ClassB1Name  
-- -- -- ClassB2Name  
-- -- ClassC1Name  
-- -- ClassC2Name

I managed to get the tree to draw the ClassA and ClassB , but couldn't figure out how to add ClassC to the Tree resources .
Please check the below source code.

Test.xaml.cs

public partial class Test : Window {    
    InitializeComponent();
    var a = new List<ClassA>{new ClassA(), new ClassA()};
    treeView.ItemsSource = a;
}

C# classes:

public class ClassA{    
    // initiate obj    
    public string Name {get; set;}     
    public List<ClassBTypes> Btypes {get; set;}     
    public List<ClassC> C {get; set;}    
}    
public class ClassBTypes{    
    public string Name {get; set;}    
    public List<ClassB> B {get; set;}   
}    
public class ClassB{    
    public string Name {get; set;}    
}     
public class ClassC{   
    public string Name {get; set;}   
}  

xaml code:

<Window.Resources>
    <DataTemplate x:Key="aKey">
        <TextBlock Text="{Binding Name}"></TextBlock>
    </DataTemplate>
    <HierarchicalDataTemplate x:Key="bKey"
               ItemsSource="{Binding B}"
               ItemTemplate="{StaticResource aKey}">
        <TextBlock Text="{Binding Name}" />
    </HierarchicalDataTemplate>
    <HierarchicalDataTemplate x:Key="bTypeKey"
               ItemsSource="{Binding Btypes}"
               ItemTemplate="{StaticResource bKey}">
        <TextBlock Text="{Binding Name}" />
    </HierarchicalDataTemplate>
</Window.Resources>   
.....     
<Grid>
   <TreeView Name="treeView" ItemTemplate="{StaticResource bTypeKey}" />
</Grid>

How to add the ClassC list from ClassA obj, I've added the below code to <Window.Resources> but how can I added it to treeView resources.

<HierarchicalDataTemplate x:Key="bTypeKey"
         ItemsSource="{Binding Btypes}"
         ItemTemplate="{StaticResource bKey}">
    <TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>

I fixed this by combine the two types of lists to CompositeCollection .
Check this answer for more details.

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