使用 MEFedMVVM 关闭窗口的最佳方法
在我的应用程序中,我有一个通过 MEFedMVVM 导入 ViewModel 的 MainWindow:
xmlns:mefed="clr-namespace:MEFedMVVM.ViewModelLocator;assembly=MEFedMVVM.WPF"
mefed:ViewModelLocator.ViewModel="MainViewModel"
现在我也有我的 ViewModel 来实现 ViewModel:
[ExportViewModel("MainViewModel")]
public class MainViewModel: ViewModelBase
在我的 ViewModel 中,我有一个用于关闭窗口的 ICommand 属性。关闭事件可以来自任何地方。在 Cinch Framework 2.0 的帮助下,我使用 Execute 方法实现了 Simplecommand。
问题
我如何从执行方法中关闭窗口?通过依赖注入,我没有构造函数,无法注册事件或将视图作为参数提供给视图模型。
编辑
但是,我认为不太好:
在方法中调用它
Application.Current.MainWindow.Close()
In my Application i have a MainWindow that import over MEFedMVVM the ViewModel:
xmlns:mefed="clr-namespace:MEFedMVVM.ViewModelLocator;assembly=MEFedMVVM.WPF"
mefed:ViewModelLocator.ViewModel="MainViewModel"
And now i have my ViewModel too that realize the ViewModel:
[ExportViewModel("MainViewModel")]
public class MainViewModel: ViewModelBase
In my ViewModel i have a ICommand property for closing the window. The event for closing can comes from anywhere. And with help from the Cinch Framework 2.0 i realize a Simplecommand with Execute methode.
Question
How can i Close the Window from my execute methode? Over the dependency injection i haven't a constructor i can't register an event or give the view as parameter to the viewmodel.
Edit
However, a possibility which I think is not nice:
Call this in the methode
Application.Current.MainWindow.Close()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过编写一个将
Window
实例作为参数传递的ICommand
来实现此目的。这里有一个很好的例子:如何将“按下 Escape 键时关闭”行为分配给项目中的所有 WPF 窗口?
发布
ICommand
最终绑定到KeyBinding
(以便 Escape 键可用于关闭窗口),但您可以将该命令绑定到任何按钮或从视图中的任何位置调用它。重要的部分是在命令参数绑定上使用RelativeSource
来引用您想要关闭的Window
编辑以响应评论
命令是一个单例,但没有要求它是 - 它只是一个单例,因为它是无状态的并且它使绑定更容易。它通过绑定获取对
Window
的引用,因此对于UserControl
您可以使用:为了能够从视图模型调用它,代码稍微复杂一些,需要一个不同的方法;可以在这里找到一个很好的示例:http://gallery.expression.microsoft.com/WindowCloseBehavior
You can achieve this by writing an
ICommand
that passes theWindow
instance in as a parameter.A good example is available here: How can I assign the 'Close on Escape-key press' behavior to all WPF windows within a project?
In that post the
ICommand
is eventually bound to aKeyBinding
(so that the Escape key can be used to close the window) but you would be able to bind the command to any button or invoke it from anywhere within the view. The important part is to use aRelativeSource
on your command parameter binding to reference theWindow
that you want to closeEdit in response to comments
The command is a singleton, but there is no requirement for it to be - it is only a singleton because it is stateless and it makes the binding easier. It acquires a reference to the
Window
through binding, so for aUserControl
you can just use:To be able to call it from view model code is slightly more complicated and needs a different approach; a good example can be found here: http://gallery.expression.microsoft.com/WindowCloseBehavior