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

霸气de小男生 提交于 2020-01-05 05:43:08

问题


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?


回答1:


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>



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/7825379/handling-a-bubbling-event-raised-from-a-modal-dialog-in-main-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!