Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 922
Vikram Avatar asked Dec 17 '22 07:12

Vikram


2 Answers

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.)

like image 179
Joe White Avatar answered Dec 18 '22 21:12

Joe White


this also helped me. I will have a event in the container of the child control and define the event in the code behind file. The event will handle all the text changed events for all the children.

       <StackPanel TextBoxBase.TextChanged="test_TextChanged" Name="test">                                    
                <userControl/>
       </StackPanel>
like image 45
Vikram Avatar answered Dec 18 '22 21:12

Vikram