这个问题似乎没有在任何地方得到完整的端到端描述:上面提供的链接是not完整解释如何定义、提出和catch从 UserControl 到父窗口的事件。这对某些人来说可能是显而易见的,但我花了一分钟时间才将这些点联系起来,所以我将分享我的发现。是的,执行此操作的方法是通过设置为 RoutingStrategy.Bubble 的自定义 RoutedEvent,但还有更多内容。
在此示例中,我有一个名为 ServerConfigs 的 UserControl,它有一个“保存”按钮。当用户单击“保存”按钮时,我想要在父Window上有一个按钮,其中包含UserControl以启用另一个按钮,该按钮称为btn_synchronize。
根据上面引用的上述 RoutedEvent 链接,在后面的 UserControl 代码中定义以下内容。
public partial class ServerConfigs : UserControl
{
// Create RoutedEvent
// This creates a static property on the UserControl, SettingsConfirmedEvent, which
// will be used by the Window, or any control up the Visual Tree, that wants to
// handle the event. This is the Custom Routed Event for more info on the
// RegisterRoutedEvent method
// https://msdn.microsoft.com/en-us/library/ms597876(v=vs.100).aspx
public static readonly RoutedEvent SettingConfirmedEvent =
EventManager.RegisterRoutedEvent("SettingConfirmedEvent", RoutingStrategy.Bubble,
typeof(RoutedEventHandler), typeof(ServerConfigs));
// Create RoutedEventHandler
// This adds the Custom Routed Event to the WPF Event System and allows it to be
// accessed as a property from within xaml if you so desire
public event RoutedEventHandler SettingConfirmed
{
add { AddHandler(SettingConfirmedEvent, value); }
remove { RemoveHandler(SettingConfirmedEvent, value); }
}
....
// When the Save button on the User Control is clicked, use RaiseEvent to fire the
// Custom Routed Event
private void btnSave_Click(object sender, RoutedEventArgs e)
{
....
// Raise the custom routed event, this fires the event from the UserControl
RaiseEvent(new RoutedEventArgs(ServerConfigs.SettingConfirmedEvent));
....
}
}
到这里就是实现示例了,上面的教程就结束了。那么如何捕获窗口上的事件并处理它呢?
在 window.xaml 中,这就是如何使用用户控件中定义的自定义 RoutedEventHandler。这与button.click等完全相同。
<Window>
....
<uc1:ServerConfigs SettingConfirmed="Window_UserControl_SettingConfirmedEventHandlerMethod"
x:Name="ucServerConfigs" ></uc1:ServerConfigs>
...
</Window>
或者在后面的 Window 代码中,您可以通过 AddHandler 设置 EventHandler,通常在构造函数中:
public Window()
{
InitializeComponent();
// Register the Bubble Event Handler
AddHandler(ServerConfigs.SettingConfirmedEvent,
new RoutedEventHandler(Window_UserControl_SettingConfirmedEventHandlerMethod));
}
private void Window_UserControl_SettingConfirmedEventHandlerMethod(object sender,
RoutedEventArgs e)
{
btn_synchronize.IsEnabled = true;
}