如何在父控件中处理子事件
在我的主窗口中,我有一个子控件(用户控件),其中包含一个文本框。如何处理主(父)窗口中子控件文本框的textchange事件。
请为我提供一些代码示例,因为我是事件路由的新手。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该能够从父控件中挂钩该事件。但由于您的父控件没有自己的
TextChanged
事件,因此您需要使用附加属性语法:并且在您的代码隐藏中:
您不必将
具体来说,
- 只是Window
上的 TextBox.TextChanged=TextBox
父级的任何控件,即父级的任何控件用户控件。该事件将依次冒泡到每个父级,一直到顶级
Window
,并且可以在整个过程中的任何位置进行处理。(请注意,如果有人挂钩该事件并设置
e.Handled = true
,该事件将不会冒泡超过该点。这对于了解您是否有多个级别的处理程序很有用。)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:and in your codebehind:
You don't have to put the
TextBox.TextChanged=
on theWindow
specifically -- just any control that's a parent of theTextBox
, i.e., any control that's a parent of yourUserControl
. The event will bubble up to each parent in turn, all the way up to the top-levelWindow
, 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.)这也对我有帮助。我将在子控件的容器中创建一个事件,并在代码隐藏文件中定义该事件。该事件将为所有子级处理所有文本更改事件。
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.
在子控件中创建一个事件 -
现在为子控件中的 TextBox 的 TextChanged 事件添加一个处理程序 -
还为此处理程序更新 XAML -
现在,您已经在子控件中创建了一个事件,该事件在 Textbox 的 textchanged 触发时触发。
现在您只需在主窗口中添加此事件的处理程序 -
Create a event in your childcontrol -
now add a handler for TextChanged event of TextBox in childcontrol -
also update XAML for this handler -
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 -