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