ItemsControl子属性不能获取父级的datacontext

时间:2014-08-27 14:21:24

标签: wpf data-binding datacontext itemscontrol

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

public BitmapImage MyImage {get; set;}

我有一个ItemsControl,其项目有一些图像和一些文本。 itemscontrol项目中的一个图像应该是MyImage。但是,ItemsControl有一个ItemsSource属性,我设置为绑定Path = 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是直接属性,绑定不会搜索直接属性。相反,它会搜索父级的数据上下文。

我该如何避免这种情况?

1 个答案:

答案 0 :(得分: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}" />