M-V-VM 设计问题.从 ViewModel 调用视图 [英] M-V-VM Design Question. Calling View from ViewModel

查看:12
本文介绍了M-V-VM 设计问题.从 ViewModel 调用视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始研究 WPF 应用程序的 M-V-VM.到目前为止,除了这个特定问题之外,一切都有意义......

I've just started looking into M-V-VM for a WPF application. Everything makes sense so far besides this particular issue...

我有一个名为 Search 的 ViewModel.此 ViewModel 绑定到数据网格并列出项目的结果.现在,我有一个命令需要显示另一个视图,即项目的详细信息.

I have a ViewModel I'll call Search. This ViewModel binds to a datagrid and lists results of items. Now, I have a command that needs to bring up another view, the item's details.

将逻辑放在搜索视图中显示另一个视图似乎不对,根本无法测试.

Putting the logic to show another view in the Search View doesn't seem right, it's not testable at all.

这是我的 ViewModel 实现,不可测试...

Here is my ViewModel implementation, which is not testable...

public class SearchViewModel
{
   public void SelectItem()
   {
     // I want to call the DetailsView from here
     // this seems wrong, and is untestable
     var detailsView = new DetailsView();
     detailsView.Show();
   }
}

在此模式中,从 ViewModel 方法显示视图的逻辑在哪里?

推荐答案

不应在 UI 层下方"的任何位置实例化视图.虚拟机存在于该领域之下,因此这不是放置该逻辑的地方(正如您已经意识到的那样).

Views should never be instantiated anywhere "below" the UI layer. VMs exist below that realm, therefore this is not the place to put that logic (as you've already realized).

几乎总会有一些 UI 级别的事件表明需要创建视图.在您的示例中,它可能是数据网格上的行(双击)单击事件.那将是新的地方并显示您的 DetailsView 窗口.

There will almost always be some UI level event that will indicate the need to create the view. In your example, it might be a row (double) click event on the datagrid. That would be the place to new-up and show your DetailsView window.

这篇关于M-V-VM 设计问题.从 ViewModel 调用视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆