4
votes

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.

3

3 Answers

11
votes

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

1
votes

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>
0
votes

Create a event in your childcontrol -

public event TextChangedEventHandler TextChanged;

now add a handler for TextChanged event of TextBox in childcontrol -

private void TextBox_TextChanged(object sender, TextChangedEventArgs args)
{
    if (TextChanged != null)
    {
        TextChanged.Invoke(this, args);
    }
}

also update XAML for this handler -

<TextBox ... TextChanged="TextBox_TextChanged" ... />

Now, you have created a event in your childcontrol that fires when the Textbox's textchanged fires.

Now you only to add a handler for this event in mainwindow -

private void ChildControl_TextChanged(object sender, TextChangedEventArgs args)
{
   //TODO: Add your further code here.
}