2014-08-27 42 views
3

我有我的视图模型属性:ItemsControl的子属性没有得到父母的datacontext

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是直接属性,绑定不搜索直接属性。相反,它会在父级的数据上下文中进行搜索。

我该如何避免这种情况?

+0

*这是因为MYIMAGE是直接财产,并绑定不搜索直接属性。相反,它会在父项的数据上下文中搜索* ...我认为你错了。这个错误仅仅意味着对象中没有'MyImage'属性,它被设置为'Binding'所在的'DataTemplate'的'DataContext'。你只需要改变你的'Binding Path',我认为@pushpraj可能为您提供了所需的正确路径。 – Sheridan 2014-08-27 15:05:13

回答

0

使用的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}" />