Is there any way for the main form to be able to intercept events firing on a subcontrol on a user control?
I've got a custom user-control embedded in the main Form of my application. The control contains various subcontrols that manipulate data, which itself is displayed by other controls on the main form. What I'd like is if the main form could be somehow informed when the user changes subcontrols, so I could update the data and the corresponding display elsewhere.
Right now, I am cheating. I have a delegate hooked up to the focus-leaving event of the subcontrols. This delegate changes a property of the user-control I'm not using elsewhere (in this cause, CausesValidation). I then have a delegate defined on the main form for when the CausesValidation property of the user control changes, which then directs the app to update the data and display.
A problem arises because I also have a delegate set up for when focus leaves the user-control, because I need to validate the fields in the user-control before I can allow the user to do anything else. However, if the user is just switching between subcontrols, I don't want to validate, because they might not be done editing.
Basically, I want the data to update when the user switches subcontrols OR leaves the user control, but not validate. When the user leaves the control, I want to update AND validate. Right now, leaving the user-control causes validation to fire twice.
Best Answer
The best practice would be to expose events on the
UserControl
that bubble the events up to the parent form. I have gone ahead and put together an example for you. Here is a description of what this example provides.UserControl1
UserControl
withTextBox1
UserControl
calledControlChanged
UserControl
register an event handler for theTextBox1
TextChangedEventTextChangeEvent
handler function I call theControlChanged
event to bubble to the parent formForm1
UserControl1
on the designerUserControl1
forMouseLeave
and forControlChanged
Here is a screenshot illustrating that the
ControlChanged
event that I defined on theUserControl
is available through the UX in Visual Studio on the parent Windows form.