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">
<Grid.Resources>
<XmlDataProvider x:Key="Company" XPath="/Company">
<x:XData>
<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" />
</Company>
</x:XData>
</XmlDataProvider>
<DataTemplate x:Key="template">
<TextBlock Text="{Binding XPath=@Name}"/>
</DataTemplate>
<CollectionViewSource x:Key="cvs" Source="{Binding Source={StaticResource Company},XPath=Person}"
Filter="src1_Filter"/>
</Grid.Resources>
<ListBox Name="lst"
ItemTemplate="{StaticResource template}"
ItemsSource="{Binding Source={StaticResource cvs}}"/>
</Grid>

//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