WPF绑定不通知更改 [英] WPF binding not notifying of changes
问题描述
首先,我有一个linqToSql实体类联系人
与 EntitySet< Booking>
财产预订。
如果我直接将此Bookings属性绑定到一个 ListView
,应用程序似乎正确地通知了 ListView $ c中的所选项目的更改$ c>,使得
$ b
//此代码工作,但是预订未排序
var binding = new Binding();
binding.Source = contact.Bookings;
reservations.SetBinding(ItemsControl.ItemsSourceProperty,binding);
但是,我似乎无法找到一种排序EntitySet的方法(见这篇文章),我试图绑定到一个Observable集合,例如:
//此代码不会通知ListView中所选项目的更改
var binding = new Binding );
binding.Source = new ObservableCollection< Booking>(contact.Bookings.OrderByDescending(b => b.TravelDate).ToList());
reservations.SetBinding(ItemsControl.ItemsSourceProperty,binding);
但是,这似乎没有正确通知评论文本框,以便更新。
如果任何人有一个解决方案,在其绑定之前或之后对数据进行排序,或者其他解决方案将非常感谢。
你应该绑定到一个 CollectionView
,而不是集合本身。这将允许您指定所需的任何排序条件。示例:
var collectionView = new ListCollectionView(contact.Bookings);
collectionView.SortDescriptions.Add(new SortDescription(TravelDate,ListSortDirection.Ascending));
var binding = new Binding();
binding.Source = collectionView;
reservations.SetBinding(ItemsControl.ItemsSourceProperty,binding);
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.
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);
这篇关于WPF绑定不通知更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!