How can I raise a parent event from a user control

2019-07-31 11:08发布

问题:

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?

回答1:

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.



回答2:

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 handler private void Window_Click(object sender, RoutedEventArgs e) in the code-behind, and it will get called when any button in the window is clicked.