WPF binding not notifying of changes

▼魔方 西西 提交于 2019-12-11 04:23:22

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/926280/wpf-binding-not-notifying-of-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!