简体   繁体   English

在应用程序中管理多个WPF视图

[英]Managing multiple WPF views in an application

So I've seen that a Navigation Service exists in WPF for maintaining a flow through an application. 所以我看到WPF中存在一个导航服务来维护应用程序的流。 I'm not really in the market for the back and forward type functionality. 我不是真正进入后退和前进型功能的市场。 I'm just looking for a good way to switch between Views when a button on a particular view is pressed. 我正在寻找一种在按下特定视图上的按钮时在视图之间切换的好方法。 I'm using MVVM, so I'm not sure if I can let the App.xaml.cs possibly contain a copy of each View or ViewModel and let a ViewModel command call into App.xaml.cs to do the switching. 我正在使用MVVM,所以我不确定是否可以让App.xaml.cs可能包含每个View或ViewModel的副本,并让ViewModel命令调用App.xaml.cs来进行切换。 Perhaps I should just handle the Click event on the button and do some flavor of this.Close(); 也许我应该只是处理按钮上的Click事件并做一些这种情况.Close(); NewWindow.Show();. NewWindow.Show();.
As with many things in WPF, this one is not intuitive to me although there probably are a couple simple solutions. 与WPF中的许多内容一样,虽然可能有一些简单的解决方案,但这对我来说并不直观。

Thanks! 谢谢!

I created a "window loader" class that the app class instantiates when the application starts. 我创建了一个“窗口加载器”类,应用程序类在应用程序启动时实例化。 The window loader has a dictionary that maintains an association of view model types and view types. 窗口加载器具有一个字典,用于维护视图模型类型和视图类型的关联。 It also has a method that takes a view model instance, resolves the view based on the view model's type, instantites the view, sets the view's datacontext to the view model then shows it. 它还有一个方法,它接受一个视图模型实例,根据视图模型的类型解析视图,立即显示视图,将视图的datacontext设置为视图模型然后显示它。 The window loader also registers for an event in the view model which is raised when the window wants to close. 窗口加载器还在视图模型中注册事件,该事件在窗口想要关闭时引发。

The window loader implements an IWindowLoader interface and a reference to it is kept in each view model (when the window loader instantiates a view model it assigns itself to a public IWindowLoader property in the view model). 窗口加载器实现IWindowLoader接口,并且在每个视图模型中保存对它的引用(当窗口加载器实例化视图模型时,它将自己分配给视图模型中的公共IWindowLoader属性)。 So any view model can cause any other view model to be shown without knowing about views and without doing the showing itself. 因此,任何视图模型都可以导致显示任何其他视图模型,而无需了解视图并且不进行显示本身。 Also, the window loader can easily be mocked for testing. 此外,可以轻松地模拟窗口加载器以进行测试。

When I went through the same process you are now, I found lots of examples of this same basic pattern. 当我经历你现在的相同过程时,我发现了许多相同基本模式的例子。 I just ended up rolling my own. 我刚刚结束自己。

A way to solve this is to introduce Controllers which are responsible for the workflow of the application. 解决此问题的方法是引入负责应用程序工作流程的控制器 They create, show and close multiple views in the application. 他们在应用程序中创建,显示和关闭多个视图。

How this works can be seen in the sample applications of the WPF Application Framework (WAF) project. 如何工作可以在WPF应用程序框架(WAF)项目的示例应用程序中看到。

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

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