一、命名约定


在Prism当中,你可以基于命名约定,便能够轻松的将View和ViewMode建立关联。前提是你已经为项目创建了Views和ViewModels文件夹(这里就突出了使用模板创建的好处了)。

例如:你的页面为ViewA,那么对应的ViewModel名称为ViewAViewModel。

​ 你的页面为HeaderView,那么对应的ViewModel名称为HeaderViewModel。

二、允许View自动装配ViewModel

<UserControl
    x:Class="Menu.Views.MenuView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:Menu.Views"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:prism="http://prismlibrary.com/"
    prism:ViewModelLocator.AutoWireViewModel="True"
    Background="Blue"
    mc:Ignorable="d">
    <Grid>
        <TextBlock
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Text="{Binding Message}" />
    </Grid>
</UserControl>


需要将添加这一句设置:

prism:ViewModelLocator.AutoWireViewModel="True"


经过上述两个步骤,我们就可以将View和View Model建立关联了。但是如果我们很任性,就是不想创建那样的文件夹,也不想要那样的名称,该怎么办呢?

三、使用ViewModelLocationProvider指定View与ViewModel的类型


不知道为什么我没有实验成功。。。所以暂不做解释。。。