WPF DataGrid – simple sorting behavior customization via ViewModel


Hi guys Smile.

I haven’t written here so long that I started to miss my blogging sessions. Today I’m going to write about WPF DataGrid sorting scenario I’ve faced recently and simple solution that has helped me.

By default, DataGrid provides out of the box sorting by certain column. Assume you have this class:

public class Order { public string Id { get; set; } public string Name { get; set; } }

As you can see, class Order has Id property, which is string. This could happen in scenario where you have some code, which you can’t change. In my case, it was Id property and values it could have were only integers.

Here is DataGrid, which binds to orders collection and displays them:

<Grid> <DataGrid ItemsSource="{Binding Orders}"/> </Grid>

In addition, here is code-behind file, which fills orders collection:

public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Orders = new List<Order> { new Order {Id = "1", Name = "Order 1"}, new Order {Id = "2", Name = "Order 2"}, new Order {Id = "8", Name = "Order 3"}, new Order {Id = "1000", Name = "Order 4"}, }; DataContext = this; } public List<Order> Orders { get; set; } }

If you run application and perform sorting by Id column, DataGrid will assume that values in this column should be compared like strings (which is not correct for column that has integers only).

I didn’t have much time to change DataGrid default sorting behavior but I assumed that it would sort items correctly if property it is bound to will have integer data type:

public class OrderViewModel { private readonly Order order; public OrderViewModel(Order order) { this.order = order; } public int Id { get { return int.Parse(order.Id); } } public string Name { get { return order.Name; } } }

Here is changed MainWindow code-behind file:

public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Orders = new List<OrderViewModel> { new OrderViewModel(new Order {Id = "1", Name = "Order 1"}), new OrderViewModel(new Order {Id = "2", Name = "Order 2"}), new OrderViewModel(new Order {Id = "8", Name = "Order 3"}), new OrderViewModel(new Order {Id = "1000", Name = "Order 4"}) }; DataContext = this; } public List<OrderViewModel> Orders { get; set; } }

If you run this application and sort by Id column, DataGrid will sort data correctlySmile.

As you can see, by introducing view model for Order I’m able to achieve additional level of flexibility for specific UI component (DataGrid in this particular case).

See you later 😉

Advertisements