Brian Triplett
Brian Triplett

Reputation: 3532

Binding to two different DataContexts in a ContextMenu

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.

Upvotes: 1

Views: 380

Answers (1)

brunnerh
brunnerh

Reputation: 184534

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.

Upvotes: 1

Related Questions