将事件从UserControl绑定到父窗口-路由事件-C#XAML

时间:2018-07-09 18:14:27

标签: c# wpf events user-controls routed-events

我在堆栈面板中有同一用户控件的多个实例,每个用户控件中都有一个按钮。

当我单击此按钮时,我希望它打开一个新窗口,然后禁用包含所有用户控件的堆栈面板,这样就不能同时打开该窗口的多个实例。然后,我希望能够在用户关闭新打开的窗口后重新启用堆栈面板。

当我的按钮位于主窗口XAML内而不是用户控件的一部分时,当前有以下代码:

private void ButtonClick(object sender, RoutedEventArgs e)
{
    RouteViewer Rv = new RouteViewer((sender as Button).Tag).ToString());
    Rv.Owner = this;
    Rv.Show();

    StackPanel.IsEnabled = false; //Disables the stackpanel 
    Rv.Closed += new EventHandler(RvClosed);
}

void RvClosed(object sender, EventArgs e)
{
    StackPanel.IsEnabled = true; //Re-enables the stackpanel
}

您可以看到问题是由于堆栈面板不在用户控件中。我一直在搜寻,怀疑答案是否与路由事件有关,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

看看这个网站here,您将要使用事件“冒泡”。

代码可能看起来像这样: C#在用户控件中:

private void ButtonClick(object sender, RoutedEventArgs e)
{
    RouteViewer Rv = new RouteViewer(((sender as Button).Tag).ToString());
    Rv.Show();

    var newEventArgs = new RoutedEventArgs(RvOpenedEvent);
    RaiseEvent(newEventArgs);
}



public static readonly RoutedEvent RvOpenedEvent = EventManager.RegisterRoutedEvent(
    "RvOpened",
    RoutingStrategy.Bubble, 
    typeof(RoutedEventHandler), 
    typeof(ClassName)); 

public event RoutedEventHandler RvOpened
{
    add { AddHandler(RvOpenedEvent, value); }
    remove { RemoveHandler(RvOpenedEvent, value); }
}

然后在主窗口XMAL中:

<UserControl:Name RvOpened="RouteViewerOpened"/>

然后在主窗口C#中:

private void RouteViewerOpened(object sender, RoutedEventArgs e)
{
    ServiceStack.IsEnabled = false;
    e.Handled = true;
}