在.NET C#中从用户控件引发父窗口上的事件

时间:2010-06-18 06:28:25

标签: .net wpf events user-controls

标题几乎解释了这个问题。首次运行应用程序时,我将用户控件加载到主窗口中。我想要做的是在单击用户控件上的按钮时在父窗口上引发事件,那么如何从用户控件上的button1_Click引发父事件?

2 个答案:

答案 0 :(得分:42)

此问题似乎没有在任何地方端到端地完整描述:上面提供的链接有关如何定义,引发和捕获的完整说明从UserControl到父窗口的事件。对某些人来说可能是显而易见的,但是我花了一分钟来连接点,所以我将分享我的发现。是的,这样做的方法是通过自定义RoutedEvent设置为RoutingStrategy.Bubble,但还有更多内容。


在这个例子中,我有一个名为ServerConfigs的UserControl,它有一个Save按钮。当用户单击“保存”按钮时,我想要一个父窗口上的按钮,其中包含用于启用另一个按钮的UserControl,该按钮称为btn_synchronize。

在后面的UserControl代码上定义以下内容,按照上面引用的上述RoutedEvent链接。

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开始,这就是如何使用用户控件中定义的Custom 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;
}

答案 1 :(得分:3)

您需要RoutedEvent link

“路由事件是根据其RoutingStrategy在视觉树中向上或向下导航的事件。路由策略可以是冒泡,隧道或直接。您可以在引发事件的元素或其他元素上连接事件处理程序使用附加的事件语法在其上方或下方:Button.Click =“Button_Click”。“