当单击按钮时,我希望使用MVVM模式打开一个新的WPF窗口吗? [英] When clicked on a button i want a new WPF window to be opened using MVVM pattern?Is this possible?

查看:66
本文介绍了当单击按钮时,我希望使用MVVM模式打开一个新的WPF窗口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我是WPF和MVVM的新手.您可以解决这个特定的Architectuarl问题吗?

当我单击一个按钮时,我想使用MVVM模式打开一个新的WPF窗口.据我了解,我不应该从视图模型中显式创建UI对象-那么如何打开新窗口?

Hi,

I''m a newbie to WPF, and MVVM. Can you help with this particular architectuarl problem?

When I click on a button I want to open a new WPF window, using the MVVM pattern. It is my understanding that I should not be explicitly creating UI objects from a View Model - so how do I open the new window?

推荐答案

并非很难实现.我假设您担心您的代码将紧密地与窗口类耦合,这意味着您在测试代码时会遇到问题.幸运的是,使用一个简单的界面就可以轻松覆盖它.

解决此问题的一种方法是使用ServiceLocator并在其中注册一个窗口管理器类.那么您可以从此处检索您的实例.现在,假设我们有一个名为IWindow的接口,我们可以创建窗口管理器,使其看起来像这样:
This is possible, and it''s not that difficult to achieve. I assume that you are worried that your code is going to be tightly coupled to a window class, which means that you will have problems testing the code. Fortunately, this is fairly easily covered using a simple interface.

One approach to solve this is to use a ServiceLocator and register a window manager class in it; then you can retrieve your instance from here. Now, suppose we have an interface called IWindow, we could create our window manager so that it looks something like this:
public class WindowManager() : IWindowManager
{
  public void Show<TWindow>(TWindow window) where TWindow : IWindow, new()
  {
    window = new window();
    ((Window)window).Show();
  }
}

public interface IWindowManager
{
  void Show<TWindow>() where TWindow : IWindow
}

public interface IWindow
{
  // This interface doesn't actually need to implement anything
  // We attach it to a window purely so we can open it using the WindowManager
}

好,到目前为止,这非常简单.在某些极端情况下,我倾向于基于 MededMVVM [

OK, that''s pretty straightforward so far. In certain extreme cases, I tend to use much more complicated window management facililty based on MefedMVVM[^], but that''s just because I have very specialist windows to manage. For normal applications, I have used the techniques I''ve just described to manage windows without any bother.

*Note: I just coded this in the browser window. It should be correct, but there may be a minor syntax issue or two there. If there are, I apologise in advance.


这篇关于当单击按钮时,我希望使用MVVM模式打开一个新的WPF窗口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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