ItemsControl的子属性不能获取父元素的数据上下文

3

我在我的视图模型中有一个属性:

public BitmapImage MyImage {get; set;}

我有一个ItemsControl,其中的项包含几张图片和一些文本。其中一个图片应该是MyImage。然而,ItemsControl有一个ItemsSource属性,我将其设置为绑定路径=Result,并且我知道ItemsControl中的所有项都采用Result的数据上下文。

因此,现在当我执行这个操作:

<Image Source="{Binding Path=MyImage}"  />

当然,我收到了错误信息:

BindingExpression path error: 'MyImage' property not found on 'object' ''KeyValuePair`2' (HashCode=-853042223)'. BindingExpression:Path=MyImage; DataItem='KeyValuePair`2' (HashCode=-853042223); target element is 'Image' (Name=''); target property is 'Source' (type 'ImageSource')

System.Windows.Data错误:40:

这是因为MyImage是直接属性,而绑定不会搜索直接属性。相反,它会在父数据上下文中搜索。

我该如何避免这种情况?


这是因为MyImage是直接属性,而绑定不搜索直接属性。相反,它在父级的数据上下文中搜索。我认为你误解了。该错误只意味着在设置为DataTemplate的DataContext的对象上没有MyImage属性,您只需要更改绑定路径,我认为@ pushpraj可能已经为您提供了所需的正确路径。 - Sheridan
1个回答

1
使用RelativeSource。
<Image Source="{Binding Path=DataContext.MyImage, RelativeSource={RelativeSource FindAncestor,AncestorType=ItemsControl}}" />

这是您可以在项模板中访问父级DataContext的方法。

编辑

我刚想到绑定可能存在另一个潜在问题,看起来你绑定了一个元素的字典。

如果图像路径在其中一个键或值中,则这可能是解决方案。

<Image Source="{Binding Path=Key.MyImage}" />

或者

<Image Source="{Binding Path=Value.MyImage}" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接