It is not possible to directly filter a collection in a binding. However, WPF allows you to filter (and sort and group) collections using CollectionViewSource .
One approach would be to define a CollectionViewSource in the resources of your ItemTemplate , which filters the ItemsSource and gets the number of elements that pass the filter by binding to the Count property of this CollectionViewSource . However, you must define your filter in codebehind. It will look something like this:
<TreeView x:Name="Tree" ItemsSource="{Binding Items}"> <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding ChildItems}"> <HierarchicalDataTemplate.Resources> <CollectionViewSource x:Key="FilteredItems" Source="{Binding ChildItems}" Filter="FilteredItems_OnFilter" /> </HierarchicalDataTemplate.Resources> <TextBlock> <TextBlock.Text> <MultiBinding StringFormat="{} {0} of {1} selected"> <Binding Path="Count" Source="{StaticResource FilteredItems}" /> <Binding Path="ItemsSource.Count" ElementName="Tree" /> </MultiBinding> </TextBlock.Text> </TextBlock> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView>
And in codebehind:
private void FilteredItems_OnFilter(object sender, FilterEventArgs e) { var item = sender as Item; e.Accepted = item.IsSelected; }
I have not tested it, but it should work as a whole. You never know with WPF though ...
Marc
source share