[英]WPF MVVM error when relating View and ViewModel
我正在学习按照本教程创建的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.
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".
The specified value cannot be assigned. The following type was expected: "DependencyObject".
是什么导致错误? 在示例代码中没有相似之处时,为什么期望DependencyObject
? 谢谢!
可能您的错误就在这里:
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.