简体   繁体   中英

WPF MVVM error when relating View and ViewModel

I am learning to create an MVVM application following this tutorial , and it has this in its entrance view:

what worked in the example

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

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

so i tried the following in my code

what didn't work in my code

<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 has an underlining error message: The type 'x:Type' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built. The type 'x:Type' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.

under <local:SingleFileViewModel/> , the error is: The specified value cannot be assigned. The following type was expected: "DependencyObject". The specified value cannot be assigned. The following type was expected: "DependencyObject".

What could be causing the errors? Why did it expect DependencyObject when there isn't anything alike in the example code? Thanks!

Probably your mistake sits here:

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

Note, that you have specified ViewModel as the DataTemplate, and the View as the DataType of DataTemplate. So it seems to me that this should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM