ItemsControl property of child item does not get parent datacontext

I have a property in my model-view:

public BitmapImage MyImage {get; set;}

      

I have an ItemsControl whose items have multiple images and some text. One of the images in the itemcontrol elements should be MyImage. However, the ItemsControl has an ItemsSource property that I have set to bind Path = Result and I know that all items in itemcontrol take the result data context.

So now when I do this:

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

      

Of course I am getting the error:

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 error: 40:

This is because MyImage is direct and the binding is not looking for direct properties. Instead, it looks in the context of the parent's data.

How can I avoid this?

+3


source to share


1 answer


use RelativeSource here

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

      

this way you can access parent DataContext in element template etc.


EDIT



I just thought of another possible binding problem, it looks like you are binding a dictionary of elements

If the image path is in one of the keys or values ​​then maybe this is the solution

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

      

or

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

      

0


source







All Articles