問題描述
在VB中過濾一個wpf collectionviewsource? (Filter a wpf collectionviewsource in VB?)
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'
參考解法
方法 1:
I'm relatively new to WPF Coding awswell. Here is what I suggest you try:
Make a filter function as follows:
Public Function FilterList(item As Object) As Boolean
Dim value as Object = item
If (Not value Is Nothing) And (Not value Is DBNull.Value) Then
If (value = "Builder") Or (value = "Office Staff") Then
Return True
Else
Return False
End If
End If
End Function
Call the function from your Window_Loaded event:
Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles MainWindow.Loaded
MyCollectionView = CollectionViewSource.GetDefaultView(Query4) 'May not be needed, IDK
MyCollectionView.Filter = New Predicate(Of Object)(AddressOf FilterList)
End Sub
Let me know if this doesn't work (May need some adjusting :D )
方法 2:
You should just need to attach the event in the XAML:
<CollectionViewSource x:Key="myCollectionView" Filter="WorkerFilter" ...>
方法 3:
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.
(by Johnny Westlake、JosephGarrone、Kent Boogaart、Shimmy Weitzhandler)