Monday, July 2, 2007

Simple filtering in ListBox / CollectionView

The following code snippet will allow you to filter out unwanted items from your collection.

<Grid Name ="grd">
<XmlDataProvider x:Key="Company" XPath="/Company">
<Company xmlns="">
<Person Name="Jack" Role="CEO"/>
<Person Name="Tim" Role="PL" />
<Person Name="Jil" Role="PL" />
<Person Name="Jimmy" Role="PM" />
<Person Name="Joy" Role="PM" />
<Person Name="Jim" Role="PL" />
<Person Name="Jack" Role="PM" />
<DataTemplate x:Key="template">
<TextBlock Text="{Binding XPath=@Name}"/>
<CollectionViewSource x:Key="cvs" Source="{Binding Source={StaticResource Company},XPath=Person}"
<ListBox Name="lst"
ItemTemplate="{StaticResource template}"
ItemsSource="{Binding Source={StaticResource cvs}}"/>

//Filter method
void src1_Filter(object sender, FilterEventArgs e)
System.Xml.XmlElement ele=e.Item as System.Xml.XmlElement;
string name=ele.Attributes[0].Value ;
if (name == "Tim") e.Accepted = true;
else e.Accepted = false;

This will display item "Tim".You may do custom filtering as you like in the filter method

No comments:

Post a Comment