关联View和ViewModel时出现WPF MVVM错误

时间:2014-11-02 07:19:55

标签: c# wpf mvvm

我正在学习在tutorial之后创建一个MVVM应用程序,它在入口视图中有这个:

示例中的功能

<UserControl.Resources>
    <DataTemplate DataType="{x:Type vm:ProductViewModel}">
        <vw:ProductView />
    </DataTemplate>

    <DataTemplate DataType="{x:Type vm:SingleBrandViewModel}">
        <vw:SingleBrandView />
    </DataTemplate>
</UserControl.Resources>

所以我在我的代码中尝试了以下内容

我的代码中没有用的功能

<Page x:Class="MvvmAttempt.FilesView"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:MvvmAttempt"
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
    Title="FilesView">

    <Page.Resources>
        <ResourceDictionary>

            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="resources/Styles.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <local:MySizeConverter x:Key="sizeConverter"/>

            <DataTemplate DataType="{x:Type local:SingleFileView}">  <--- error here
                <local:SingleFileViewModel/>   <--- error here
            </DataTemplate>

        </ResourceDictionary>
    </Page.Resources>
    ... other stuff ...
</Page>

x:Type有一个下划线错误消息:The type 'x:Type' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.

<local:SingleFileViewModel/>下的

,错误为:The specified value cannot be assigned. The following type was expected: "DependencyObject".

可能导致错误的原因是什么?当示例代码中没有任何相似内容时,为什么期望DependencyObject?谢谢!

1 个答案:

答案 0 :(得分:1)

可能你的错误就在这里:

<DataTemplate DataType="{x:Type local:SingleFileView}">  <--- error here
    <local:SingleFileViewModel/>   <--- error here
</DataTemplate>

请注意,您已将ViewModel指定为DataTemplate,并将View指定为DataTemplate的DataType。所以在我看来这应该有效:

<DataTemplate DataType="{x:Type local:SingleFileViewModel}">
    <local:SingleFileView/>
</DataTemplate>