Hi @RogerSchlueter-7899 ,
Dispatcher.BeginInvoke delays when you hook the handlers, it does not stop WPF from immediately doing two normal initialization actions:
- ListBox
SelectionChangedfires because the control sets or synchronizes its selection (e.g. selects the first item) during data binding. -
CollectionViewSource.Filterfires because as soon as a filter handler is attached WPF refreshes the view to ensure no unfiltered data is shown.
So the first calls are inevitable. The practical fix is to make those early invocations harmless until your initialization finishes.
I suggest using a readiness flag (plus optional DeferRefresh batching) so the first automatic refresh and selection change are ignored, then performing one real refresh once ready.
Private _ready As Boolean = False
Private Sub LoadMe(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
cvsPeople = CType(Resources("cvsPeople"), CollectionViewSource)
cvsPeople.Source = ocPeople
Using cvsPeople.DeferRefresh()
AddHandler cvsPeople.Filter, AddressOf PeopleFilter
AddHandler lbxPeople.SelectionChanged, AddressOf SelectPerson
End Using ' Filter + selection may fire; _ready still False
_ready = True
cvsPeople.View.Refresh() ' First real filter pass
End Sub
Private Sub PeopleFilter(sender As Object, e As FilterEventArgs)
If Not _ready Then
e.Accepted = True
Return
End If
Dim p = TryCast(e.Item, Person)
e.Accepted = (p IsNot Nothing) AndAlso ShouldShowPerson(p)
End Sub
Private Sub SelectPerson(sender As Object, e As SelectionChangedEventArgs)
If Not _ready Then Return
' Real selection logic here
End Sub
Hope this helps. Feel free to reach out if there's any problem