如何从 WPF 中的用户控件引发父事件?
我有一个加载到父窗口中的用户控件,并且我想在单击用户控件上的按钮时引发父事件。如何通过 WPF 中的用户控件与父级进行通信?
I have a user control that is loaded into the parent window, and I want to raise a parent event when a button on the user control is clicked. How can I communicate with the parent through my user control in WPF?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想到的第一种方法是让您的 UserControl 引发父窗口正在侦听的事件。然后家长可以提出您想要的事件。
First way that comes to mind is to have your UserControl raise an event that the parent window is listening to. The parent can then raise the event you want.
您正在查找路由事件。
按钮上的 Click 事件是一个 RoutedEvent,因此如果您的 UserControl 有一个按钮,那么您可以在窗口中处理该事件。在 XAML 中将属性
ButtonBase.Click="Window_Click"
添加到窗口,并在代码隐藏中添加处理程序private void Window_Click(object sender, RoutedEventArgs e)
,然后单击窗口中的任何按钮时都会调用它。You're looking for Routed Events.
The Click event on Button is a RoutedEvent, so if your UserControl has a button then you can handle that event in the window. Add an attribute
ButtonBase.Click="Window_Click"
to the Window in your XAML and a handlerprivate void Window_Click(object sender, RoutedEventArgs e)
in the code-behind, and it will get called when any button in the window is clicked.