Search code examples
c#wpfxamlmvvmdatagrid

WPF - How do I sort a DataGridTemplateColumn with a list of strings as content


I have the following code:

    <DataGrid ItemsSource="{Binding FilteredLectureViewModels}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
            <!-- Profs -->
            <DataGridTemplateColumn Header="Profs">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate DataType="viewModels:LectureViewModel">
                        <ItemsControl ItemsSource="{Binding Profs}">
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <TextBlock Text="{Binding ProfString}"/>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

I want the datagrid to sort its content by clicking on the header 'Profs' like it's working for a DataGridTextColumn with the header 'Name' already by default. I know the attribute 'SortMemberPath' of the DataGridTemplateColumn, but i don't know how to use that in this situation.


Solution

  • In bindings, you can use brackets [ ] to supply an index for a collection as part of the binding path. Upon testing, this same approach seems to work for SortMemberPath:

    <DataGridTemplateColumn Header="Profs" SortMemberPath="Profs[0].ProfString">
    

    This sorts based on the ProfString property of the first item in Profs. I'm not sure why you would want to sort based on the first item in a collection, but this does it.