Search code examples
c#wpflistviewtreeviewcelltemplate

c# WPF TreeView in ListView via CellTemplate


I am new to WPF and XAML..

I want to add an TreeView into a ListView Element with a CellTemplate..

I want to bind each ListViewItem to a Custom class called "Symbol"

This Class has an Property called "Name" and a Property called "Images".

"Name" is just a String, which should be the root Element of the TreeView..

"Images" is a List of Strings.

Each entry of this list should be an Children of this TreeView..

And please do not just leave a code snippet, i want to understand how CellTemplates work!

Thank you!

<Grid>
    <ListView x:Name="listview" HorizontalAlignment="Left" Height="326" Margin="0,33,0,0" VerticalAlignment="Top" Width="499">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Symbols" Width="200"  >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <TreeView>
                                <!--
                                    what to be done here?
                                -->
                                </TreeView>
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
    <Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="250" Margin="504,33,0,0" VerticalAlignment="Top" Width="250">
        <Border x:Name="image_preview" HorizontalAlignment="Center" Height="250" VerticalAlignment="Center" Width="250"/>
    </Border>

</Grid>

Solution

  • First you should bind ListView to a collection of Symbol objects. Now, every cell of your ListView is bound to Symbol object. If I understand you correctly, each Symbol should be a TreeView with root node header displaying Name property and collection of children displaying Images strings.

    This can be achieved this way:

    <TreeView >
        <TreeViewItem Header="{Binding Name}" ItemsSource="{Binding Images}" />    
    </TreeView>