wpf - UserControl的DataContext:直接设置为viewmodel
问题描述
我有一个 wpf 用户控件和一个对应的视图模型(ChamberVm)。
在 viewmodel 中有一个名为“UnitStatus”的属性,但我遇到了绑定错误:
System.Windows.Data Error: 40 : BindingExpression path error: 'UnitStatus' property not found on 'object' ''String' (HashCode=-1814504727)'. BindingExpression:Path=UnitStatus; DataItem='String' (HashCode=-1814504727); target element is 'VacGram' (Name='sysdgm'); target property is 'UnitStatus' (type 'KeyValuePair`2')
我注意到错误可能与控件标题部分中的 DataContext 设置有关:
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:dgm="clr-namespace:VacSym;assembly=VacSymDgm"
xmlns:v="clr-namespace:VacViews"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="400"
DataContext="ChamberVm">
<Grid Name="gridMain">
<Grid.RowDefinitions>
<RowDefinition Height="0*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="15"></RowDefinition>
</Grid.RowDefinitions>
<DockPanel Grid.Row="1">
<DockPanel x:Name="pnlDgm" Background="Transparent" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<dgm:VacGram x:Name="sysdgm" UnitStatus="{Binding UnitStatus}" DiagramFile="{Binding DiagramFile}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</DockPanel>
. . .
我想知道:
1、为什么这不正确(?)
DataContext="ChamberVm"
2、错误信息中的“String”是什么意思:
...not found on 'object' ''String'
婷
解决方案
那作业
DataContext="ChamberVm"
将字符串分配给"ChamberVm"
DataContext 属性。
为了分配 ChamberVm 类的实例,您必须编写以下内容,并带有适当的命名空间前缀:
<UserControl ...>
<UserControl.DataContext>
<v:ChamberVm/>
</UserControl.DataContext>
...
</UserControl>
通常,您应该完全避免显式分配 DataContext 属性。
您可以将 UserControl 放在 DataTemplate 中,该 DataTemplate 应用于例如 ContentControl,该 ContentControl 具有分配给其 Content 属性的 ChamberVm 对象。然后将自动设置 UserControl 的 DataContext。
推荐阅读
- node.js - 如何在命令行终端(vty)中运行电子二进制文件
- android - 如何使用语音交互打开活动?
- java - 使用 JAXB 将 XML 标记内容存储到不同的变量
- java - Postgresql 触发器约束
- encoding - 如何通过管道将 tail -f 传送到 iconv 命令?
- vb.net - 从 SSIS 调用 SSRS:某些 PDF 文件已损坏
- postgresql - 如何为向上迁移添加枚举值的 Postgresql 编写向下迁移?
- rspec - 您可以将匹配器传递给 rspec 中的共享示例吗?
- sql-injection - zap 工具显示安全漏洞,但我们在源代码中找不到这些漏洞?
- spring-boot - 在没有 Spring Boot Application 主类的项目中测试 Spring Data Repository