我有一个应用程序,允许用户创建同一个用户控件的多个实例,其中包含一个listview,该列表视图绑定到自定义数据类型的ObservableCollection。在用户单击标题后,我将listview正确排序,但它会对绑定到ObservableCollection的所有视图进行排序。
我的问题是,有没有办法在ObservableCollection的视图上实现排序,还是有另一种方法来克隆ObservableCollection的内容(注意:ObservableCollection不断被后台服务添加到必须实时显示。
我按如下方式对集合进行排序:
ICollectionView dataView = CollectionViewSource.GetDefaultView(sourceList.ItemsSource);
dataView.SortDescriptions.Clear();
SortDescription sd = new SortDescription(sortBy, direction);
dataView.SortDescriptions.Add(sd);
我的列表视图的项目来源设置如下:
myListView.ItemsSource = ServiceManager.Instance.ActiveObjects;
我不希望维护相同ObservableCollection的多个实例。要求用户能够拥有此用户控件的多个实例,所以很遗憾,我无法轻松解决这个问题并将其限制为单个实例。
对此的任何帮助都将非常感谢,提前致谢。
答案 0 :(得分:3)
您的错误是将ItemsSource
属性直接设置为ServiceManager.Instance.ActiveObjects
属性:
myListView.ItemsSource = ServiceManager.Instance.ActiveObjects;
相反,您应该为每个ICollectionView
的数据集创建单独的ListView
实例。此示例改编自以下链接页面:
private ICollectionView _customerView;
public ICollectionView Customers
{
get { return _customerView; }
}
public CustomerViewModel()
{
IList<YourClass> customers = ServiceManager.Instance.ActiveObjects;
_customerView = CollectionViewSource.GetDefaultView(customers);
}
...
<ListBox ItemsSource="{Binding Customers}" />
您可以在WPF Tutorial.NET网站的How to Navigate, Group, Sort and Filter Data in WPF页面上找到更多详细信息。