2017-02-18 66 views
0

我想在WPF应用程序中链接两个CollectionViewSource。 有什么办法可以让以下事情发挥作用?链接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> 
+0

你能解释一下为什么你正在尝试做的这个?也许有更好的方法去做呢? – Kelly

+0

这基本上是一个更复杂的对象树的摘录。设想控制A通过CollectionViewSource过滤其数据并将其传递给控件B的ItemsSource。它的工作原理是控件B将通过将其ItemsSource绑定到其自己的CollectionViewSource来尝试执行自己的过滤,分组或排序。 –

回答

1

CollectionViewSource不过滤其源集合,它过滤的视图。无论何时绑定到WPF中的某些数据集合,都始终绑定到自动生成的视图,而不是绑定到实际的源集合本身。视图是一个实现接口的类,提供了对集合中的当前项目进行排序,过滤,分组和跟踪的功能。

因此,而不是试图“链接”两CollectionViewSources在一起,你应该将它们绑定到同一个源集合:

<CollectionViewSource x:Key="ItemsViewA" Source="{Binding Items}" /> 
<CollectionViewSource x:Key="ItemsViewB" Source="{Binding Items}" /> 

然后,他们可以相互独立地筛选意见。

如果你想在控制A的过滤器上应用控制B的过滤器,你应该实现在CollectionViewSourceFilter事件处理这样的逻辑,如:

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 */; 
} 
+0

因此基本上没有办法链接它们,因为CollectionViewSource的Source属性不支持ICollectionView。 –