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>
1

1 Answer 1

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.