wpfdata-bindingsortingentityset

WPF binding not notifying of changes


I have a WPF sorting/binding issue. (Disclaimer: I am very new to WPF and databinding so apologise if I am asking a really dumb question :-))

Firstly, I have a linqToSql entity class Contact with an EntitySet<Booking> property Bookings on it.

If I directly bind this Bookings property to a ListView, the application seems to correctly notify of changes to the selected item in the ListView, such that a textbox with {Binding Path=Bookings/Comments} updates correctly.

// This code works, but Bookings is unsorted  
var binding = new Binding();
binding.Source = contact.Bookings;
bookings.SetBinding(ItemsControl.ItemsSourceProperty, binding);

However, as I can't seem to be able to find a way to sort an EntitySet (see this post), I am trying to bind instead to an Observable collection, e.g:

// This code doesn't notify of selected item changes in the ListView
var binding = new Binding();
binding.Source = new ObservableCollection<Booking>(contact.Bookings.OrderByDescending(b => b.TravelDate).ToList());
bookings.SetBinding(ItemsControl.ItemsSourceProperty, binding);

But this doesn't seem to notify the comments textbox correctly such that it updates.

If anyone has a solution for either sorting the data before or after its bound, or another solution that will work that would be much appreciated.


Solution

  • You should bind to a CollectionView rather than the collection itself. That will allow you to specify whatever sorting criteria you require. Example:

    var collectionView = new ListCollectionView(contact.Bookings);
    collectionView.SortDescriptions.Add(new SortDescription("TravelDate", ListSortDirection.Ascending));
    var binding = new Binding();
    binding.Source = collectionView;
    bookings.SetBinding(ItemsControl.ItemsSourceProperty, binding);