我正在尝试学习 MVVM 模式 (C#),我有 Windows 窗体背景。我正在使用 MVVM Light 工具包,到目前为止我认为它很棒。 我已经制作了几个小型应用程序,但是我正在努力解决的一件事是引入第二个 View 。
我想(例如)在我的 MainViewModel 上有一个按钮,它通过 RelayCommand 打开一个新窗口 - 让我们说一个“关于”窗口。为此,我在网上做了数小时的研究,但似乎无法让我的 AboutViewModel 与我的 AboutView 通信/显示我的 AboutView。
我在 AboutView.xaml 的代码隐藏构造函数中放置了一个接收信使 - 但是我无法让它接收来自 AboutViewModel 的任何消息,因此无法使其成为“Show()”。
如果有人有使用多个 View 的 Mvvm Light WPF 应用程序的示例,那就太好了:)
最佳答案
我认为有两种方法可以轻松做到这一点
第一个是使用 Popup
而不是新的 Window
。例如,我经常在我的 ViewModel
中为 PopupContent
和 IsPopupVisible
设置属性,并在我想显示我的 Popup 时随时设置这些值
控制。例如,ShowAboutPopup
中继命令可能会运行如下内容:
void ShowAboutPopup()
{
PopupContent = new AboutViewModel();
IsPopupVisible = true;
}
您可以使用 Popup
对象或自定义 UserControl
来显示它。我更喜欢使用自己的 custom Popup UserControl ,通常最终看起来像这样:
<Window>
<Canvas x:Name="RootPanel">
<SomePanel>
<!-- Regular content goes here -->
</SomePanel>
<local:PopupPanel Content="{Binding PopupContent}"
local:PopupPanel.IsPopupVisible="{Binding IsPopupVisible}"
local:PopupPanel.PopupParent="{Binding ElementName=RootPanel}" />
</Canvas>
</Window>
PopupContent
属性是一个ViewModel
(比如一个AboutViewModel
),DataTemplates
用来告诉WPF 使用特定的 Views
ViewModels
<Window.Resources>
<DataTemplate DataType="{x:Type local:AboutViewModel}">
<local:AboutView />
</DataTemplate>
</Window.Resources>
另一种方法是让某种 ApplicationViewModel
在启动时运行,并负责整个应用程序状态,包括打开的窗口。
通常我更喜欢有一个包含ContentControl
的ApplicationView
来显示当前页面
<Window>
<ContentControl Content="{Binding CurrentViewModel}" />
</Window>
不过它也可以用来管理多个窗口。如果您确实使用它来管理多个 Window
对象,请注意这不是一个纯 ViewModel
,因为它需要访问一些特定于 View 的对象,并引用 UI对象不是 ViewModel
应该做的事情。例如,它可能订阅接收 ShowWindow
消息,并且在接收到这些消息后,它会创建指定的 View 并显示它,也可能隐藏当前窗口。
就个人而言,我尽量避免使用多个窗口。我通常的方法是拥有一个包含任何页面的一致应用程序对象的 View ,以及一个包含变化的动态内容的 ContentControl
。我有一个 example using this navigation style on my blog如果你有兴趣
关于c# - MVVM Light - 多个 ViewModel(并将它们连接起来),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12062313/