WPF MVVM 并将视图模型传递给视图

问题描述:

我对 WPF 还很陌生,现在我正在努力适应 MVVM 模式.现在我有一个简单的应用程序,其中我有一组显示在网格中的 ViewModel.当我双击网格中的行时,我想显示 ViewModel 的详细信息视图.

I am pretty new to WPF and right now I am trying to get used to the MVVM pattern. Right now I have a simple application in which I have a collection of ViewModels that I display in a grid. When I doubleclick on the row in the grid I want to show a details View of the ViewModel.

我现在遇到的问题是我已经有一个完全实例化的 ViewModel,但我似乎无法将它传递到视图中.当我尝试加载该视图时,它变成空的.我已经发现这是因为当一个 View 被加载时,它会创建它自己的支持 ViewModel 的实例.所以显然我需要解决这个行为,并在创建时以某种方式将实例化的 ViewModel 传递到 View 中.我可以在 View 中使用一个构造函数,它接受一个 ViewModel 并在那里设置数据源.但是,采用这种方法但是意味着我需要在 ViewModel 中构造 View,从而使 ViewModel 知道该视图.这是我想避免的事情,因为我正在努力维护 MVVM 模式.

The problem I am having right now is that I already have a fully instanced ViewModel, but I can't seem to pass it into the view. When I try to load that View it turns up empty. I already found out that this is due to the fact that when a View gets loaded it creates it's own instance of the backing ViewModel. So obviously I need to get around this behaviour and somehow pass the instanced ViewModel into the View when it is created. I could use a constructor in the View that takes a ViewModel and set the datasource in there. However, taking this approach but would mean that I need to construct the View in the ViewModel and thus making the ViewModel aware of the View. This I something I would like to avoid since I am trying to uphold the MVVM pattern.

那么在这种情况下我该怎么办?我应该打破 MVVM 模式,还是有一些适合 MVVM 模式的漂亮而干净的解决方案?

So what should I do in this case? Should I just break the MVVM pattern or are there some nice and clean sollutions for this that fit in the MVVM pattern?

将视图模型传递给视图的方法有很多种,如您所称,或将视图模型设置为 WindowUserControl 的 code>DataContext,其他人可能会这样称呼它.最简单的就是这样:

There are many ways of passing a view model to a view, as you call it, or setting a view model as the DataContext of either a Window or UserControl, as others may call it. The simplest is just this:

在视图构造函数中:

public partial class SomeView
{
    InitializeComponent();
    DataContext = new SomeViewModel();
}

更多的 MVVM 方法可能是在 App.xaml 中为每个视图模型定义 DataTemplates,定义每个视图模型将使用哪个视图:

A more MVVM way might be to define DataTemplates in App.xaml for each view model that defines which view each will use:

<DataTemplate DataType="{x:Type YourViewModelsPrefix:YourViewModel">
    <YourViewsPrefix:YourView />
</DataTemplate>
...
<DataTemplate DataType="{x:Type YourViewModelsPrefix:AnotherViewModel">
    <YourViewsPrefix:AnotherView />
</DataTemplate>

现在,每当框架遇到这些视图模型类的实例时,它就会呈现关联的视图.您可以使用像这样的 ContentControl 通过具有您的视图模型类型的属性来显示它们:

Now whenever the Framework comes across an instance of these view model classes, it will render the associated view. You can display them by having a property of the type of your view model using a ContentControl like this:

<ContentControl Content="{Binding YourViewModelProperty}" />

甚至在这样的集合中:

<ListBox ItemsSource="{Binding YourViewModelCollectionProperty}" />