简体   繁体   English

WPF带有MVVM的多个窗口

[英]WPF Multiple windows with MVVM

What is the common\\best practice when working with multiple windows with MVVM? 使用MVVM处理多个窗口时,最常见的\\最佳实践是什么? I have one window with a button, when clicking on the button I want to open a second window and close the first window. 我有一个带有按钮的窗口,单击该按钮时,我想打开第二个窗口并关闭第一个窗口。 How can I do that with MVVM? 我该如何使用MVVM? should I have a MainViewModel instance for each window? 每个窗口都应该有一个MainViewModel实例吗? or should I have only one instance of the MainViewModel that all the windows will use? 还是应该只有所有窗口将使用的MainViewModel的一个实例?

Thanks! 谢谢!

Caliburn.Micro suggest a concept called Conductors that handles this situation pretty well. Caliburn.Micro建议使用一个称为Conductor的概念来很好地处理这种情况。

you can manage the lifetime of a screen or multiple screens by making your MainViewModel inherit from Conductor<T>.Collection.OneActive or Conductor<T>.Collection.AllActive depending how many active windows can be shown at once. 您可以通过使MainViewModel继承来自Conductor<T>.Collection.OneActiveConductor<T>.Collection.AllActive来管理一个或多个屏幕的生命周期,具体取决于一次可以显示多少个活动窗口。

It hold Items which is the currently conducted items and provides OnActivate and OnDeactive methods where you can implement your on activation and deactivation logic. 它持有Items是目前进行的项目,并提供OnActivateOnDeactive方法,在那里你可以实现你的激活和失活的逻辑。

This is a very strong framework, but it will require you to incorporate Caliburn.Micro in your project and bootstrapping it which may be kind of a hassle if you are working with a different MVVM framework. 这是一个非常强大的框架,但需要您将Caliburn.Micro纳入项目并进行自举,如果使用其他MVVM框架,可能会很麻烦。 However you can still implement this concept or look for similar implementations in other frameworks. 但是,您仍然可以实现此概念,或在其他框架中寻找类似的实现。

Try to use "Frame" and "Pages" inside it. 尝试在其中使用“框架”和“页面”。 I think that is the best solution for you. 我认为这是最适合您的解决方案。

You have two options: 您有两种选择:

  1. open a new View by using the code-behind (I do not like this solution, since it is not very MVVM compliant) 使用后台代码打开一个新视图(我不喜欢这种解决方案,因为它与MVVM不太兼容)
  2. you can use Dependency Injection 你可以使用依赖注入

I do not know if you are using a specific MVVM framework (like Caliburn.Micro, MVVM-light and so on), so if you are looking for a generic solution which uses Dependency Injection, you can find tons of good articles. 我不知道您是否正在使用特定的MVVM框架(例如Caliburn.Micro,MVVM-light等),因此,如果您正在寻找使用依赖注入的通用解决方案,那么您会发现很多不错的文章。

I suggest you to read these ones: 我建议您阅读以下内容:

  1. WPF Master Details MVVM Application WPF Master Details MVVM应用程序
  2. Showing Dialogs When Using the MVVM Pattern 使用MVVM模式时显示对话框
  3. Cinch V2: Version 2 of my Cinch MVVM framework: Part 1 of n - just the "MEFedMVVM and ViewModel/Service Resolution" chapter Cinch V2:我的Cinch MVVM框架的版本2:n的第1部分 -仅“ MEFedMVVM和ViewModel /服务分辨率”一章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM