views:

1446

answers:

2

Hi, I want to filter a collectionviewsource using a filter I've written, but I'm not sure how I can apply the filter to it?

Here is my collection view source:

    <Grid.Resources>
        <CollectionViewSource x:Key="myCollectionView" 
           Source="{Binding Path=Query4, Source={x:Static Application.Current}}">
            <CollectionViewSource.SortDescriptions>
                <scm:SortDescription PropertyName="ContactID" 
                                     Direction="Descending"/>
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
    </Grid.Resources>

I have implemented a filter as such:

    Private Sub WorkerFilter(ByVal sender As Object, ByVal e As FilterEventArgs)

    Dim value As Object = CType(e.Item, System.Data.DataRow)("StaffSection")

    If (Not value Is Nothing) And (Not value Is DBNull.Value) Then
        If (value = "Builder") Or (value = "Office Staff") Then
            e.Accepted = True

        Else

            e.Accepted = False
        End If
    End If
End Sub

So how can I get the CollectionViewSource filtered by the filter on load? Could you please give all hte code I need (only a few lines I figure) as I'm quite new to coding.

Thanks guys

EDIT: For the record,

  <CollectionViewSource x:Key="myCollectionView" Filter="WorkerFilter" ... />

gives me the error:

Failed object initialization (ISupportInitialize.EndInit). 'System.Windows.Data.BindingListCollectionView' view does not support filtering. Error at object 'myCollectionView'

A: 

You should just need to attach the event in the XAML:

<CollectionViewSource x:Key="myCollectionView" Filter="WorkerFilter" ...>

HTH, Kent

Kent Boogaart
Thanks, but when I try that I get hte following error:Failed object initialization (ISupportInitialize.EndInit). 'System.Windows.Data.BindingListCollectionView' view does not support filtering. Error at object 'myCollectionView'
The Source of your CollectionView does not support filtering because it is based on a BindingList. I'm not sure why BindingList doesn't support filtering, but a plain old List does. Try changing your source to a List<T> rather than BindingList<T>.
Kent Boogaart
Uuuhhh.... sorry I'm not sure how'd I'd go about that. I assume "Source="{Binding Path=Query4, Source={x:Static Application.Current}}"" is my binding list? This refers to a datatable called Query4. How could I turn this into an ordinary list?thanks
A: 

I had the same issue, till I decided to do the following and works good, I donno what the cons are:

<Window 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:data="clr-namespace:System.Windows.Data;assembly=PresentationFramework">

    <CollectionViewSource
    x:Key="FilteredBindingListCollection"
    CollectionViewType="{x:Type data:ListCollectionView}" />

</Window>

Hope this was helpful.

Shimmy