处理主窗口中模式对话框引发的冒泡事件
我的 WPF 应用程序中有一个模式对话框,允许用户登录服务器。该对话框仅包含一个用户控件,用于处理所有登录内容(UI、Web 服务调用以及在调用返回时引发路由事件)。
一切正常,我可以在对话框中处理我的事件(登录成功后关闭对话框)。但是,我无法在主应用程序中处理该事件(用户登录后我应该刷新 UI)。
如何在引发事件的窗口之外拦截此类路由事件(如果可能的话)?如果不可能,通常的处理方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
路由事件不会从新窗口发送给所有者。 RoutedCommands 也不能直接工作。但是
Binding
可以工作!当您设置
childWindow.OwnerWindow = Application.Current.MainWindow
时,childWindow 通过其OwnerWindow
属性在逻辑上连接到 MainWindow。您可以使用它来绑定到
OwnerWindow
的 ViewModel 命令并执行它。Routed Events dont from new windows to owners. RoutedCommands also wont work directly. But
Binding
s can work!When you set
childWindow.OwnerWindow = Application.Current.MainWindow
the childWindow gets logically connected to the MainWindow via itsOwnerWindow
property.You could use that to bind to
OwnerWindow
's ViewModel command and execute that.路由事件不会从一个窗口转到另一个窗口。
在子窗口上定义公共 CLR 事件。当主窗口实例化子窗口时,它应该在显示子窗口之前连接该事件的处理程序。然后孩子只需要在适当的时间提出这个事件即可。
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.
我不明白如何在不同窗口之间自动冒泡路由事件,因为它们不在同一逻辑树中。复杂的 UI 应用程序倾向于处理此类视图间通信的方式是通过 EventAggregator 模式的某种实现,因此,如果您发现需要在视图之间进行大量通信,那么它可以是处理此类场景的更干净的方法。 Prism 框架包含一个
EventAggregator
实现,但如果需要,针对简单场景的手写实现应该不会太困难。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 anEventAggregator
implementation but a hand-written one for a simple scenario shouldn't be too difficult if required.