Search code examples
wpfeventsevent-handlingroutesevent-bubbling

How to handle child event in parent control


In my main window, I have a child control(user control) which contains a text box . How can I handle the textchange event of the text box of child control in main(parent) window.

Please provide me some example with code as I am new to routing of events.


Solution

  • You should just be able to hook the event from the parent control. But since your parent control doesn't have a TextChanged event of its own, you'll need to use attached-property syntax:

    <Window ...
            TextBox.TextChanged="ChildTextBoxChanged">
    

    and in your codebehind:

    private void ChildTextBoxChanged(object sender, TextChangedEventArgs args)
    {
        ...
    }
    

    You don't have to put the TextBox.TextChanged= on the Window specifically -- just any control that's a parent of the TextBox, i.e., any control that's a parent of your UserControl. The event will bubble up to each parent in turn, all the way up to the top-level Window, and can get handled anywhere along the way.

    (Note that if anyone hooks the event and sets e.Handled = true, the event won't bubble past that point. Useful to know if you have handlers at multiple levels.)