如何使用中介模式在 MVVM 中打开/显示新窗口?
我对 WPF 和 WPF 非常陌生。 MVVM 范式,我正在努力吸收它。我遇到的问题看起来很多 MVVM 初学者都面临着同样的问题。似乎没有简单的方法。因此,为了保持问题域简单,这里只是一项实验工作。
我有一个主窗口,上面有一个“新建”按钮。我想在单击此按钮时显示 NewWindow.xaml 的实例。我如何从 MainWindowViewModel 执行此操作?中介模式有帮助吗?请建议任何好的实施参考。
我的主窗口和主窗口上还有一个“关闭”按钮。我想在单击此应用程序时退出该应用程序。我再次需要帮助:(
I'm very much new in WPF & MVVM paradigm and i'm trying hard to absorb it. The problem i'm having looks like a lot of MVVM beginers face the same & it seems there's no simple approach. So, to keep the problem domain simple here's just an experimental work.
I have a MainWindow with a "New" button on it. I want to show an instance of a NewWindow.xaml when i click on this button. How can i do this from MainWindowViewModel? Can mediator pattern help? Please suggest any good implementation reference.
I also have a "Close" button on the MainWindow & i want to exit the application when i click this one. And I need help again :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不久前也遇到过同样的问题。
至少我使用了一种非常简单的方法并且我很满意。 这里是我的解决方案。
在你的视图模型中你只需要编写一行代码:
i did have the same problem a while ago.
at least i use a very simple approach and i'm happy with. here is my solution.
in your viewmodel you just have to write one line of code:
我将对话框代码放入视图的CodeBehind 中。我仍然通过 ViewModel 路由命令,但 ViewModel 调用 View 的实现并获取结果。
假设我有 MainWindow View (xaml) 和 MainWindow ViewModel,并且我想保存一个文件。
在代码隐藏视图 (MainWindow.xaml.cs) 中,我添加代码来创建对话框并返回保存文件名:
在 ViewModel 中,我有一个 DoSaveFile() 方法:
在 MainWindow.xaml 中,我有一个绑定到委托的按钮命令:
与 MVP 一样,此实现很啰嗦,但对于测试和关注点分离来说它非常有效。对我来说,将窗口打开机制留给 View 类是有意义的,即使它感觉有点像活动视图。
I put dialog code into the View's CodeBehind. I still route the command through the ViewModel, but the ViewModel calls the View's implementation and gets the result.
Suppose I have MainWindow View (xaml), and a MainWindow ViewModel and I want to save a file.
In the codebehind View (MainWindow.xaml.cs) I add the code to create the dialog and return the save filename:
In the ViewModel I have a DoSaveFile() method:
In the MainWindow.xaml I have a button bound to to the delegate command:
Like MVP, this implementation is chatty, but it works really well for test and separation of concerns. To me, it makes sense to leave the mechanics of window opening to the View class, even thought it feels a bit like an active-view.