Search code examples
c#wpfeventsrouted-events

Handling a bubbling event raised from a modal dialog in main window


I have a modal dialog in my WPF application that allows a user to login to a server. The dialog simply contains a User Control that handles all the login stuff (UI, web service call, and raising a routed event when the call returns).

All works nicely and I can handle my event in the dialog (close the dialog when login successfull). However, I am not able to handle the event in my main application (I should refresh the UI once the user has logged in).

How can one intercept such routed events outside the window where it has been raised (if even possible)? If not possible, what is the usual way to handle that?


Solution

  • Routed Events dont from new windows to owners. RoutedCommands also wont work directly. But Bindings can work!

    When you set childWindow.OwnerWindow = Application.Current.MainWindow the childWindow gets logically connected to the MainWindow via its OwnerWindow property.

    You could use that to bind to OwnerWindow's ViewModel command and execute that.

      <Window x:Class="...ChildWindow"
              ... >
          <Button Command="{Binding Path=OwnerWindow.DataContext.SaveCommand,
                                    RelativeSource={RelativeSource
                                        AncestorType={x:Type Window}}}"
                  Content="Execute Owner's Save Command" />
      </Window>