我想在WPF应用程序中链接两个CollectionViewSource。有什么办法让下面的事情起作用吗?
MainWindow.xaml.cs:
using System.Collections.Generic;
using System.Linq;
using System.Windows;
namespace ChainingCollectionViewSource
{
public partial class MainWindow : Window
{
public IEnumerable<int> Items => Enumerable.Range(0, 10);
public MainWindow()
{
DataContext = this;
InitializeComponent();
}
}
}MainWindow.xaml:
<Window x:Class="ChainingCollectionViewSource.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<CollectionViewSource x:Key="ItemsViewA"
Source="{Binding Items}" />
<CollectionViewSource x:Key="ItemsViewB"
Source="{Binding Source={StaticResource ItemsViewA}}" />
</Window.Resources>
<ListBox ItemsSource="{Binding Source={StaticResource ItemsViewB}}" />
</Window>发布于 2017-02-19 19:14:24
CollectionViewSource不过滤它的源集合,它过滤视图。每当您绑定到WPF中的某些数据集合时,总是绑定到自动生成的视图,而不是绑定到实际的源集合本身。视图是实现System.ComponentModel.ICollectionView接口并提供排序、筛选、分组和跟踪集合中当前项的功能的类。
因此,与其试图将两个CollectionViewSources“链接”在一起,不如将它们绑定到同一个源集合:
<CollectionViewSource x:Key="ItemsViewA" Source="{Binding Items}" />
<CollectionViewSource x:Key="ItemsViewB" Source="{Binding Items}" />然后,它们可以相互独立地过滤视图。
如果要在控件A的过滤器之上应用控件B的过滤器,则应在CollectionViewSource的CollectionViewSource事件处理程序中实现此逻辑,例如:
private void ItemsViewA_Filter(object sender, FilterEventArgs e)
{
e.Accepted = Include(e.Item as YourType);
}
private bool Include(YourType obj)
{
//your filtering logic...
return true;
}
private void ItemsViewB_Filter(object sender, FilterEventArgs e)
{
var item = e.Item as YourType;
e.Accepted = Include(item) && /* your additional filtering logic */;
}https://stackoverflow.com/questions/42309794
复制相似问题