Search code examples
c#wpfeventsuser-controlsrouted-events

Bind an event from a UserControl into the parent Window- Routed events - C# XAML


I have multiple instances of the same User Control inside a stack panel, with a button in each user control.

When I click this button I want it to open a new window and then disable the stack panel containing all the user controls, such that multiple instance of this window can not be opened at the same time. I then want to be able to re-enable the stack panel upon the user closing the newly opened window.

Currently I have this code, when my button is inside of the Main Window XAML and not a part of the User Control:

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
}

As you can see the issue is due to the Stack Panel not being apart of the User Control. I've been googling and suspect the answer is something to do with routed events, any help would be appreciated.


Solution

  • Have a look at this website here, you will want to use event "Bubbling".

    The code may look something like this: C# In User Control:

    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); }
    }
    

    Then in the Main Window XMAL :

    <UserControl:Name RvOpened="RouteViewerOpened"/>
    

    Then in the Main Window C#:

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