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, theListBox(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
SelectionChangedevent. - Since you just attached your handler, it gets called right away which makes it look like
AddHandleritself 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:
- Use a flag to ignore events during initialization.
- Attach the handler later (e.g., with
Dispatcher.BeginInvoke) so it only subscribes after the control is fully loaded. - 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.