locked
Filter a Listbox bound to SampleDataSource RRS feed

  • Question

  • I have searched extensively before posting, but I could not find a solution.

    If I create a SampleDataSource and bind it to a Listbox, how can I filter the listbox to only show the items that match the text that a user has entered into a separate Textbox.

    Thanks
    Wednesday, February 3, 2010 8:25 PM

All replies

  • Hi dloop2

    You brief question seems contain several sub-questions without details. I have to make some assumptions when showing code demo.

    I am not sure the detail of the SampleDataSource, lets take it as a simple one that generated by Blend, which default has a collection with 2 properties. I assume you only use the property1 which is string type. I assume you drag the collection to the listbox, which Blend will generate the databinding code, including: ItemsSource="{Binding Collection}"

    In the SampleData folder, find the SampleDataSource.xaml.cs , open it, find the partial code of:
     public class SampleDataSource : System.ComponentModel.INotifyPropertyChanged
     {
      ...
      public ItemCollection Collection
      { ...
      }
     }

    As you can see, that "Collection" property is the listbox databinding to.

    What you can do is change the xaml to ItemsSource="{Binding MatchedCollection}" , and add another property in that class:

    private ItemCollection _MatchedCollection = new ItemCollection();
      public ItemCollection MatchedCollection
      {
    	get{
    		foreach (ItemCollection item in Collection)
    		{
    			if (Textbox.text.Contain(item.Property1)) _MatchedCollection.add item;
    		}
    		return _MatchedCollection;
    	}
      }
    
    





    Thanks, Harry Huang [MSFT]
    • Proposed as answer by Harry.MSFT Wednesday, February 10, 2010 6:06 AM
    Wednesday, February 10, 2010 6:05 AM