1

I'm trying to bind to a property of a container from inside a DataTemplate. A simplified version of my markup looks like:

<Grid> <Grid.Resources> <DataTemplate DataType="{x:Type myCustomItem}"> <!--Visual stuff--> <StackPanel> <StackPanel.ContextMenu> <ContextMenu> <MenuItem Header="Add Item" Command="{Binding myCustomItemsICommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type CustomContainerType}}, Path=ContainerProperty}"/> </ContextMenu> </StackPanel.ContextMenu> </StackPanel> </DataTemplate> </Grid.Resources> <CustomContainerType/> </Grid> 

My approach is based on this post but it doesn't seem to be working. The issue seems to arise from the placement of the ContextMenu within the visual tree. Basically I am trying to bind the Command to the DataContext of the DataTemplate but bind the CommandParameter to a DataContext outside the DataTemplate.

1 Answer 1

1

ContextMenus are not in the same visual tree as the rest of the controls, there are a few questions regarding how to do bindings accross that boundary but this might be somewhat difficult without specifying names.

ElementName fails as well because of the lacking tree connection, but you could use x:Reference in the Binding.Source instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! The Source={x:Reference Name=theElementName} approach worked.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.