首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >链式CollectionViewSource

链式CollectionViewSource
EN

Stack Overflow用户
提问于 2017-02-18 00:48:03
回答 1查看 181关注 0票数 1

我想在WPF应用程序中链接两个CollectionViewSource。有什么办法让下面的事情起作用吗?

MainWindow.xaml.cs:

代码语言:javascript
复制
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:

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-19 19:14:24

CollectionViewSource不过滤它的源集合,它过滤视图。每当您绑定到WPF中的某些数据集合时,总是绑定到自动生成的视图,而不是绑定到实际的源集合本身。视图是实现System.ComponentModel.ICollectionView接口并提供排序、筛选、分组和跟踪集合中当前项的功能的类。

因此,与其试图将两个CollectionViewSources“链接”在一起,不如将它们绑定到同一个源集合:

代码语言:javascript
复制
<CollectionViewSource x:Key="ItemsViewA" Source="{Binding Items}" />
<CollectionViewSource x:Key="ItemsViewB" Source="{Binding Items}" />

然后,它们可以相互独立地过滤视图。

如果要在控件A的过滤器之上应用控件B的过滤器,则应在CollectionViewSourceCollectionViewSource事件处理程序中实现此逻辑,例如:

代码语言:javascript
复制
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 */;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42309794

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档