Here's an example of sorting records through a WPF Datagrid Column Header.
Customer class:
Code:
public class Customer
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String Address { get; set; }
public Boolean IsNew { get; set; }
public DateTime CompleteDate { get; set; }
public Boolean? IsSubscribed { get; set; }
public Customer(String firstName, String lastName,
String address, Boolean isNew, Boolean? isSubscribed, DateTime completeDate)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Address = address;
this.IsNew = isNew;
this.IsSubscribed = isSubscribed;
this.CompleteDate = completeDate;
}
public static List<Customer> GetSampleCustomerList()
{
return new List<Customer>(new Customer[4] {
new Customer("Jarred", "Brown",
"15 Truman St. Maya Subdivision",
false, true, DateTime.Now.Date),
new Customer("Homer", "Thompson",
"34 West Fifth Street, Apartment 25",
false, false, DateTime.Now.Date.AddDays(-5)),
new Customer("William", "Rodge",
"22 East Seabord Lane, Sunset Ville",
true, null, DateTime.Now.Date.AddDays(-5)),
new Customer("Tanner", "Chen",
"59 South Express Lane, Apartment 90",
true, true, DateTime.Now.Date.AddDays(10))
});
}
}
MainWindow code behind(Binding of ItemSource)
Code:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
dgCustomer.ItemsSource = Customer.GetSampleCustomerList();
}
XAML
Code:
<DataGrid Name="dgCustomer" ItemsSource="{Binding}" AutoGenerateColumns="False" Grid.Column="1" >
<DataGrid.Columns>
<DataGridTemplateColumn SortMemberPath="LastName" Header="Last Name" CanUserSort="true">
<DataGridTemplateColumn.CellTemplate >
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<Binding Path="LastName"/>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn SortMemberPath="FirstName" Header="First Name" CanUserSort="true">
<DataGridTemplateColumn.CellTemplate >
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<Binding Path="FirstName" />
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn SortMemberPath="Address" Header="Address" CanUserSort="true" Width="280">
<DataGridTemplateColumn.CellTemplate >
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<Binding Path="Address" />
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn SortMemberPath="CompleteDate" Header="Complete Date" CanUserSort="true">
<DataGridTemplateColumn.CellTemplate >
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<Binding Path="CompleteDate" ConverterCulture="en-GB" StringFormat="{}{0:MM/dd/yyyy}"/>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Records Sorted by Last Name.