我有一个具有数据网格的 wpf 应用程序(MVVM 样式)。我使用 Entity Framework 作为我的模型。在这个数据网格中,我有一列来自另一个表中的值。我使用导航属性来获取这个值。当数据网格加载有问题的列时,会显示正确的值,但在输出窗口中仍然会生成绑定(bind)错误:
System.Windows.Data Error: 40 : BindingExpression path error: 'product_category' property not found on 'object' ''tracking_stock_EA7F46EC8AD7F155921357AA6714C6C20BE807C4760A3B6DFC4FAC1954CA8119' (HashCode=49385318)'. null
数据网格行绑定(bind)到的对象称为 追踪库存其导航属性为 产品 ,它本身的导航属性为 products_category 我用来获取 product_category.chrProdCtgry
这是概述 EF 设计的图像:
所以我的文本 block 在数据网格模板列中的绑定(bind)如下:
<DataGridTemplateColumn Header="CATEGORY" SortMemberPath="product.product_category.chrProdCtgry" ToolTipService.ToolTip="Category of the product" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding product.product_category.chrProdCtgry}" Style="{StaticResource FTC_DetailLabelSub}" Width="120" TextWrapping="NoWrap"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
现在,一切正常,列可以排序,文本 block 中的文本具有应有的值。
问题:
当一切正常时,为什么会抛出这个绑定(bind)错误?
编辑#1:
我试图删除排序声明:
SortMemberPath="product.product_category.chrProdCtgry"
绑定(bind)错误仍然存在
编辑#2:
所以我尝试将 IsAsync=True 添加到数据网格本身的文本 block 和集合绑定(bind)中。现在,在我对类别列进行排序之前,不会显示文本 block 值。此外,上面列出的绑定(bind)错误仍然存在,但现在生成了一个新错误:
System.Windows.Data Error: 17 : Cannot get 'product_category' value (type 'product_category') from 'product' (type 'product_83A5741ABC5EE6395B89B7B4B384137E8CF95991EF9918BD4525EF06B774469E'). BindingExpression:Path=product.product_category.chrProdCtgry; DataItem='tracking_stock_EA7F46EC8AD7F155921357AA6714C6C20BE807C4760A3B6DFC4FAC1954CA8119' (HashCode=2011918); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String') TargetInvocationException:'System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
编辑#3:
Sheridan 的帖子让我想到当从数据库上下文创建数据网格的集合时数据不存在。于是我又回到了 Entity Framework 的“GET”函数,通过以下三种方式强制包含导航属性,都没有摆脱绑定(bind)错误:
1
Dim trackingList = Await Context.tracking_stock.Include("product").ToListAsync
Return New ObservableCollection(Of tracking_stock)(trackingList)
2
Dim trackingList = Await Context.tracking_stock.Include("product.product_category").ToListAsync
Return New ObservableCollection(Of tracking_stock)(trackingList)
3
Dim trackingList = Await Context.tracking_stock.Include("product").Include("product.product_category").ToListAsync
Return New ObservableCollection(Of tracking_stock)(trackingList)
最佳答案
如果您使用异步数据访问操作,有时会发生这种情况......这可能是数据到达之前的错误并且是数据绑定(bind)的。我遇到了这个问题,我通过添加 IsAsync="True"
解决了它给我的Binding
.
更新>>>
根据对您问题的第一次编辑,如果您删除了排序声明并且错误仍然存在,那么这不是您的错误的原因。在您的整个解决方案中搜索 product.product_category.chrProdCtgry
...必须在某处的绑定(bind)中使用此文本的另一个实例。我正要回家,但如果有时间,我稍后会尝试再看看这个。
关于数据网格中的 Wpf 绑定(bind)错误仍然显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18618357/