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?

有帮助吗?

解决方案

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>

其他提示

Routed events won't go from one window to another.

Define a public CLR event on your child window. When the main window instantiates the child, it should hook up a handler for that event before showing the child. The child then just needs to raise this event at the appropriate time.

I don't see how you could automatically bubble a routed event between different windows since they're not in the same logical tree. The way that complex UI applications tend to handle inter-view communication of this kind is through some implementation of the EventAggregator pattern, so if you find that you need a lot of communication between views then it can be a much cleaner way to deal with these kind of scenarios. The Prism framework contains an EventAggregator implementation but a hand-written one for a simple scenario shouldn't be too difficult if required.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top