01
Feb
12

wp7 Collectionviewsource filtering

Having read a recent question on the App Hub Forums I decided to update my previous post on CollectionViewSource http://babaandthepigman.wordpress.com/2011/07/03/wp7-collectionviewsource-sorting-a-listbox/ to enable filtering.

So, I added a text box to enter the filter string,

 

cvs2

 

And the following code to implement the filtering…

     private void FilterBoxTextChanged(object sender, TextChangedEventArgs e)
     {
           
Source.View.Filter = o =>
                                    
{
                                        
var item = o as Item;
                                        
if (item != null)
                                         {
                                            
return item.Text.Contains(filterBox.Text);
                                         }
                                        
return false;
                                     };
        }

and we get filtered results…

 

cvs2-2

Here’s the updated project https://skydrive.live.com/redir.aspx?cid=4f1b7368284539e5&resid=4F1B7368284539E5!436&parid=4F1B7368284539E5!123


3 Responses to “wp7 Collectionviewsource filtering”


  1. February 11, 2012 at 7:21 pm

    I tried this code but a NullreferenceException is generated. Then I checked and found that Source.View is null.
    why it is null ? do we need to set view property ? if yes how ?

    • May 8, 2012 at 8:34 pm

      I was having this problem as well using this method in a ViewModel rather than in the page and found that the main problem was due to newing and setting .Source in the VM ctor. I moved these few lines of code to the get accessor of the public CollectionViewSource property and it eliminated the exception.

      However, filtering is not working still; the items are enumerated and set to a bool value of true is returned for the correct items in the ObservableCollection, but they seem to be ignored, as the list is not filtered. Even calling CollectionViewSource.View.Refresh() makes no difference. :/ Any suggestions?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.