0

In a WPF application, if I have an observable collection displayed in a grid/list view. And the user can request to filter what is visible by a predefined set of rules. What would be better performance wise:

  1. For each item to add a binding to its visibility with a converter
  2. Or changing the entire source to be the filtered collection.

I don't want the converter to do any logic - it will probably be a simple check after I have already done the filter in the view model. I don't have any code because I want to understand what is better and then implement that.

Maya S
  • 127
  • 1
  • 9
  • 2
    [Which is faster?](https://ericlippert.com/2012/12/17/performance-rant/) – James Thorpe Sep 21 '16 at 09:09
  • 1
    @Maya S My suggestion is to use trigger in your style. and manage the visibility of the listboxitem by well defined DataTrigger. In this way you won't walk through the collection of item(like in case of a filtered collection), and no need any Converters. Let me know if you need an example. – Ilan Sep 21 '16 at 14:38
  • @Ilan Thanks for the comment. It was one of my options but when searching through the web between converter vs trigger - most articles suggested that converters are better. That is why I'm looking to decide between these 2 since I need the best performance. – Maya S Sep 21 '16 at 15:04
  • 1
    @MayaS pros http://stackoverflow.com/questions/11152313/should-i-use-wpf-converter-or-trigger, cons http://stackoverflow.com/questions/19466354/wpf-triggers-vs-converter, third approach not so useful in your case http://stackoverflow.com/questions/5508159/datatrigger-vs-databinding-with-converter-performance-wise. I prefer trigger in this case. – Ilan Sep 21 '16 at 19:37

1 Answers1

4

I think the best way to do what you are trying to achieve is to use CollectionViewSource.

var view = new CollectionViewSource();
view.Filter += Filter;
view.Source = source;

void Filter(object sender, FilterEventArgs e)
{
    if (e.Item != null)
        e.Accepted = false; //condition here        
}

CollectionViewSource : https://msdn.microsoft.com/fr-fr/library/system.windows.data.collectionviewsource(v=vs.110).aspx

You can find an example there :

https://stackoverflow.com/a/9618387/5703316

Community
  • 1
  • 1
Quentin Roger
  • 6,410
  • 2
  • 23
  • 36
  • From my understanding the CollectionViewSource is a control, right? Unfortunately I can't change the controls the application uses. Thanks for your reply, didn't know about this control. – Maya S Sep 21 '16 at 15:07
  • After some research, I came across [this question](http://stackoverflow.com/questions/1280704/how-can-i-sort-a-listbox-using-only-xaml-and-no-code-behind) and the solution was to use a CollectionViewSource like you suggested - but as a static resource and then use it as a source binding to a grid/list. I will accept this answer – Maya S Sep 25 '16 at 10:56