Josh Smith 的 MVVM 示例中的视图是如何构建的?

问题描述:

作为 WPF 和 MVVM 的新手,我正在学习 Josh Smith 的文章关于 MVVM 模式和随附的示例代码.

Being new to both WPF and MVVM, I'm studying Josh Smith's article on the MVVM pattern and the accompanying sample code.

我可以看到应用程序是在 app.xaml.cs 中通过构造一个 MainWindow 对象,将它连接到一个 MainWindowViewModel 对象而启动的然后显示主窗口.到目前为止一切顺利.

I can see that the application is started in app.xaml.cs by constructing a MainWindow object, wiring it to a MainWindowViewModel object and then showing the main window. So far so good.

但是,我找不到任何实例化 AllCustomersViewCustomerView 类的代码.在这些视图的构造函数上使用查找所有引用"一无所获.我在这里错过了什么?

However, I can't find any code which instantiates the AllCustomersView or CustomerView classes. Using "find all references" on the constructors of those views comes up with nothing. What am I missing here?

WPF 的 DataTemplate 发挥了神奇的作用.例如,当您在资源字典(通常在 app.xaml 中)中使用以下 DataTemplate 的 CustomerViewModel 实例设置 Contentcontrol 的内容时.然后你会在 UI 中看到 CustomerView 用户控件.

WPF's DataTemplate is doing the magic. For example when you set content of a Contentcontrol with an instance of CustomerViewModel with the below DataTemplate in your resource dictionary (usually in app.xaml). Then you are gonna see CustomerView usercontrol coming up in the UI.

<DataTemplate DataType="{x:Type vm:CustomerViewModel}">
  <vw:CustomerView />
</DataTemplate>