Effect of an AddHandler

RogerSchlueter-7899 1,526 Reputation points
2025-10-07T16:52:50.8433333+00:00

Consider this code:

Private Sub LoadMe(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
	cvsPeople = CType(Resources("cvsPeople"), CollectionViewSource)
	cvsPeople.Source = ocPeople
	AddHandler lbxPeople.SelectionChanged, AddressOf SelectPerson
End Sub
Private Sub PeopleFilter(sender As Object, e As FilterEventArgs)
	<<Some filtering code>>
End Sub

I was surprised to discover that the AddHandler line doesn't just assign a delegate to the event, it also invokes it. Is there a way to do the assigning part but not the invoking part?

Developer technologies | VB
{count} votes

Answer accepted by question author
  1. Varsha Dundigalla(INFOSYS LIMITED) 3,960 Reputation points Microsoft External Staff
    2025-10-08T11:37:35.27+00:00

    Thank you for reaching out.

    AddHandler itself does not invoke your event handler it only registers it. The reason your SelectPerson method is running immediately afterward is due to the control’s own initialization logic, not because of AddHandler.

    In your case, lbxPeople.SelectionChanged is raised automatically when the control is initialized or data bound:

    • When you set cvsPeople.Source = ocPeople, the ListBox (lbxPeople) gets its items.
    • WPF’s default behavior is to automatically select the first item in a list-based control.
    • That automatic selection raises the SelectionChanged event.
    • Since you just attached your handler, it gets called right away which makes it look like AddHandler itself invoked it.

    Key Point:

    The event is firing because the ListBox has just selected an item during setup, not because AddHandler executed your handler.

    If you want to avoid reacting to that initial setup event, you have a few options:

    1. Use a flag to ignore events during initialization.
    2. Attach the handler later (e.g., with Dispatcher.BeginInvoke) so it only subscribes after the control is fully loaded.
    3. Temporarily unsubscribe/subscribe around the setup code.

    Let me know if you need any further help with this. We'll be happy to assist.

    If you find this helpful, please mark this as answered.


1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 82,061 Reputation points Volunteer Moderator
    2025-10-08T03:46:18.53+00:00

    Most likely the form has code to load the select list after the load event. See the designer file. This load fires the select event.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.