Datagrid in WPF – 1 column default sorted

NOTE: Using a CollectionViewSource
will provide you with more power and control in these situations.
When you’re learning WPF I recommend understanding how to use
CollectionViewSource to solve this problem along with other collection
related problems like Grouping and Filtering.

EDIT: This may be due to changes in the specification. This answer is based upon using .NET 4.0, I’ve not researched whether this solution will work in older versions of the framework.

Given this XAML

<DataGrid x:Name="LibraryView" ItemsSource="{Binding Path=Elements[Persons]}" IsReadOnly="True" LoadingRow="dg_LoadingRow">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Path=Element[Name].Value}" IsReadOnly="True" />
            <DataGridTextColumn Header="Score" Binding="{Binding Path=Element[Score].Value}" IsReadOnly="True" />
            <DataGridTextColumn Header="Date" Binding="{Binding Path=Element[Date].Value}" IsReadOnly="True" />
        </DataGrid.Columns>
    </DataGrid>

All you need to do is pick a column and specify a sorting direction for that column.

<DataGrid x:Name="LibraryView" ItemsSource="{Binding Path=Elements[Persons]}" IsReadOnly="True" LoadingRow="dg_LoadingRow">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Path=Element[Name].Value}" IsReadOnly="True" />
                <DataGridTextColumn Header="Score" Binding="{Binding Path=Element[Score].Value}" IsReadOnly="True" SortDirection="Ascending" />
                <DataGridTextColumn Header="Date" Binding="{Binding Path=Element[Date].Value}" IsReadOnly="True" />
            </DataGrid.Columns>
        </DataGrid>

This will default the sorting to the 2nd column in the ascending direction.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)