views:

535

answers:

2

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.

+2  A: 

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);

HTH, Kent

Kent Boogaart
Thanks, this sorts fine but it still fails to notify of selected item changes for some reason.
Hainesy
A: 

Hainesy,

Does the Booking object implement INotifyPropertyChanged to notify change in Comments property?

If not, you cannot expect TextBox which is bound to Comments property to be updated automatically when Comments change

Using ObservableCollection in this case will only get you the benefit of updating the view with changes when Booking objects are added or deleted from the collection

-Rajesh

moonlightdock
The comments for a booking never change. What changes is the currently selected booking in the view. This all works fine when I bind directly to the unsorted EntitySet.
Hainesy