kat*_*tit 12 c# collections wpf binding mvvm
我将ItemsControl绑定到CollectionViewSource.这是代码:
this.Trucks = new ObservableCollection<Truck>();
foreach (var truck in DataRepository.Trucks.Where(t => t.ReadyDate.Date.Equals(this.Date)))
{
this.Trucks.Add(truck);
}
this.TrucksSource = new CollectionViewSource { Source = this.Trucks };
this.TrucksSource.SortDescriptions.Add(new SortDescription("ReadyAddress.Region.RegionNumber", ListSortDirection.Ascending));
this.TrucksSource.SortDescriptions.Add(new SortDescription("TruckId", ListSortDirection.Ascending));
Run Code Online (Sandbox Code Playgroud)
当我最初绑定 - 排序工作.当我将项目添加到ObservableCollection时 - 它被插入适当的位置,这很好.但是当我改变我排序的属性时 - 这个项目没有在列表中"移位".
ReadyAddress.Region.RegionNumber
正确引发INotifyPropertyChanged并在绑定字段中看到它,但顺序不会改变.我是否期望一些不应该发生的事情,或者有更好的方法来解决这个问题?
较晚的答案,但使用4.5 ListCollectionView(ListBox和CollectionViewSource.View的默认实现)添加了新属性,以实现此目的。
您可以使用IsListSorting和ListSortingProperties启用自动重新排序。不,它不会重建视图
list.SortDescriptions.Add(new SortDescription("MyProperty", ListSortDirection.Ascending));
list.IsLiveSorting = true;
list.LiveSortingProperties.Add("MyProperty");
Run Code Online (Sandbox Code Playgroud)
当属性MyProperty
更改时,这应该采取措施。
您是否尝试过刷新您的collectionviewsource?
this.TruckSource.View.Refresh();
Run Code Online (Sandbox Code Playgroud)
我发现提到的所有答案,View.Refresh()
但对于大型列表来说这不是很好的解决方案.我最终做的是Remove()
和Add()
这个项目.然后在没有重新加载整个列表的情况下正确地重新定位.
谨慎!它适用于我的工作,但在您的情况下删除对象和重新添加可能会导致副作用,具体取决于您的代码编写方式.在我的情况下,它是一个带有UI效果的列表,其中新项目显示转换,所以刷新将显示整个列表中的转换,其中删除/添加很好地显示项目重新定位的方式.
归档时间: |
|
查看次数: |
7699 次 |
最近记录: |