Search code examples
wpfsortingdatagriddatagridtemplatecolumn

Sorting Datagrid with DataGridTemplateColumn


I am using a DataGrid and the ItemSource is Bound to a list of strings. The problem is that the sorting is not working. The header is enabled and can be clicked but the data is not sorted.

<DataGrid ItemsSource="{Binding CollectionNames}" SelectedItem="{Binding CurrentName}" SelectionUnit="FullRow" CanUserAddRows="False" AutoGenerateColumns="False" SelectionMode="Single" >
                <DataGrid.Columns>
                    <DataGridTemplateColumn Width="400" CanUserSort="True"  SortMemberPath="Name">
                        <DataGridTemplateColumn.HeaderTemplate>
                            <DataTemplate>
                                <TextBlock Text="Name" Foreground="#FF40A4E0" HorizontalAlignment="Left" VerticalAlignment="Center"></TextBlock>
                            </DataTemplate>
                        </DataGridTemplateColumn.HeaderTemplate>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ContentControl>
                                    <TextBlock HorizontalAlignment="Left" VerticalAlignment="Center" Text="{Binding}"/>
                                </ContentControl>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
                <DataGrid.CellStyle>
                    <Style TargetType="DataGridCell">
                        <Setter Property="BorderThickness" Value="0"/>
                    </Style>
                </DataGrid.CellStyle>
            </DataGrid>

I think the problem is SortMemberPath="Name" but I dont know what to put instead of "Name"


Solution

  • Simply you can set SortMemberPath=".". This usage is similar when you set the Binding's Path to ".", which means the whole item will be bound, in this case the whole item will be used as the input value for the sorter.