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

查看:77
本文介绍了我可以过滤来自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) ?

推荐答案

您可以使用

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天全站免登陆