我可以从 xaml 过滤集合吗? [英] Can I filter a collection from xaml?

查看:17
本文介绍了我可以从 xaml 过滤集合吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 wpf-mvvm 应用程序.

I have a wpf-mvvm application.

我的视图模型中有一个可观察的集合

I have an observable collection in my viewmodel

public ObservableCollection<BatchImportResultMessageDto> ImportMessageList { get; set; } 

BatchImportResultMessageDto"包含两个属性..

"BatchImportResultMessageDto" contains two properties..

结果类型..和消息.结果类型可以是成功或失败.

result type..and message. Result type can be success or failure.

我需要在一个列表框中显示成功...而在另一个列表框中显示失败.

I need to display success in one list box ..and failure in another listbox.

我可以做到这一点..通过在视图模型中有 2 个可观察的集合来保存成功/失败.

I can do this..by having 2 observable collections in viewmodel to hold success/failure.

public ObservableCollection<BatchImportResultMessageDto> ImportFailureMessageList { get; set; } // To hold the failure messages.
public ObservableCollection<BatchImportResultMessageDto> ImportSuccessMessageList { get; set; } // To hold the sucess messages.

但是有没有其他更好的方法可以过滤它(没有新的两个集合)?

But is there any other better way so that i can filter it (without new two collections) ?

推荐答案

您可以使用 CollectionViewSource 并使其成为您的视图模型的属性,并直接从 XAML 绑定到它而不是您的 ImportMessageList 集合.将您的 ImportMessageList 集合设置为 CollectionViewSource 的来源,然后配置一个谓词来对 CollectionViewSource 进行过滤.

You can use a CollectionViewSource and make it a property of your view model, and bind to that instead of your ImportMessageList collection directly from the XAML. Set your ImportMessageList collection as the Source of the CollectionViewSource, and then configure a predicate to do your filtering on the CollectionViewSource.

类似于:

private ICollectionView messageListView;
public ICollectionView MessageListView
{
    get { return this.messageListView; }
    private set
    {
      if (value == this.messageListView)
      {
        return;
      }

      this.messageListView = value;
      this.NotifyOfPropertyChange(() => this.MessageListView);
    }
}

...


this.MessageListView = CollectionViewSource.GetDefaultView(this.ImportMessageList);
this.MessageListView.Filter = new Predicate<object>(this.FilterMessageList);

...

public bool FilterMessageList(object item)
{
  // inspect item as message here, and return true 
  // for that object instance to include it, false otherwise
  return true;
}

这篇关于我可以从 xaml 过滤集合吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆