0

I have a ListBox with a ContextMenu and I am trying to bind to the Tag. I am able to use RelativeSource/FindAncestor to bind to the Tag from the ItemTemplate but this same approach doesn't work for the ContextMenu.

I looked through the Live Visual Tree in Visual Studio and I see the ListBox Items but I don't see the ContextMenu. What is the proper way to do this binding if the ListBox is not an Ancestor of the ContextMenu in the Visual Tree?

Note: I intend to create a ContextMenu in the Page.Resources that I can use in more than one ListBox so I do not want to use ElementName to bind to specific controls.

<ListBox Grid.Row="1"
         x:Name="SetupStepsList"
         VerticalAlignment="Stretch"
         KeyDown="ListBox_KeyDown"
         Tag="This is the tag"
         Style="{StaticResource GenericListBox}"
         SelectedValue="{Binding ActiveStep, Mode=TwoWay}"
         ItemContainerStyle="{StaticResource TightListBox}"
         ItemsSource="{Binding SelectedStation.SetupSteps, Mode=OneWay}">

   <ListBox.ContextMenu>
      <ContextMenu>
         <MenuItem Header="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBox}}, Path=Tag}" >
            <MenuItem.Icon>
               <iconPacks:PackIconMaterial Kind="Plus"
                                           Style="{StaticResource MenuIconStyle}"/>
            </MenuItem.Icon>
         </MenuItem>
      </ContextMenu>
   </ListBox.ContextMenu>

   <ListBox.ItemTemplate>
      <DataTemplate>
         <StackPanel>
            <TextBlock AllowDrop="False"
                       Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBox}}, Path=Tag}"/>
         </StackPanel>
      </DataTemplate>
   </ListBox.ItemTemplate>

</ListBox>
thatguy
  • 21,059
  • 6
  • 30
  • 40
Blake
  • 47
  • 6
  • Does this answer your question? [Binding from context menu item to parent control](https://stackoverflow.com/questions/3878620/binding-from-context-menu-item-to-parent-control) – Keithernet Aug 20 '20 at 16:21

1 Answers1

0

A ContextMenu is not part of the same visual tree as the ListBox, therefore RelativeSource bindings do not work. You can do this instead:

<MenuItem Header="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}">

This works, because the PlacementTarget of the ContextMenu is the parent ListBox.

thatguy
  • 21,059
  • 6
  • 30
  • 40