1
votes

I'm trying to add a context menu to a ListBoxItem. I'm using ListBox.ItemTemplate and DataTemplate (with a Grid) to define the layout of the item and the ListBoxItem is styled.

In a search that this should be the way to go:

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="ContextMenu">
            <Setter.Value>
                <ContextMenu>
                    <MenuItem Header="Rename" Click="Rename_Click" />
                </ContextMenu>
            </Setter.Value>
        </Setter>
    </Style>
</ListBox.ItemContainerStyle>

But this throws an XamlParseException/InvalidCastException saying

Couldn't cast an object of the type
System.Windows.Controls.MenuItem to the type
System.Windows.Controls.Grid

I tried adding the context menu to the Grid in the ItemTemplate, but then it only works when you click on one of the elements in the Grid (there is some empty space) (or if I add a background to the Grid, but that overrides/"covers" the styling, for hover & selected, of the Item itself)

I can't find any similar issues when searching, and I can't figure out the logic of the Exception..

2
Can you pls post the code for the ItemTemplate?Mark Feldman

2 Answers

1
votes

You could overcome this by defining the ContextMenu as a resource:

    <ListBox>
        <ListBox.Resources>
            <ContextMenu x:Key="cm">
                <MenuItem Header="Rename" Click="Rename_Click" />
            </ContextMenu>
        </ListBox.Resources>
        <ListBox.ItemTemplate>
            ...
        </ListBox.ItemTemplate>
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="ContextMenu" Value="{StaticResource cm}" />
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>
0
votes

Use the TargetType="ListBoxItem" string of code. Because the coding langauge needs to know the Listbox!