C #: Listbox Contextmenu for Listboxitems (WPF)

I want my list in WPF to be contextual. I did this with the context menu for the entire list, but you can use richt-click to get the context menu, even if you don't click on an item.

I found something on google, but that didn't work.

I tried something like this:

<ListBox Margin="5" ItemsSource="{Binding}"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}"> <TextBlock.ContextMenu> <ContextMenu> <MenuItem Header="{Binding Name}" Click="MenuItemName_Click"/> <MenuItem Header="{Binding Capital}" Click="MenuItemCapital_Click"/> <MenuItem Header="{Binding Population}" Click="MenuItemPopulation_Click"/> </ContextMenu> </TextBlock.ContextMenu> </TextBlock> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 

I tried it with a text block, as in the example, with other elements, as in other textbooks, I got tired of it and much more, but nothing worked. There are no context menus for my list items :(

later I tried something like this:

  <ListBox.ItemTemplate> <DataTemplate> <ListBoxItem> <ListBoxItem.ContextMenu> <ContextMenu> <MenuItem/> </ContextMenu> </ListBoxItem.ContextMenu> </ListBoxItem> </DataTemplate> </ListBox.ItemTemplate> 

But that didn't work either.

Can someone give me a hint / working example :)?

Thank you

+6
c # wpf contextmenu listbox listboxitem
source share
1 answer

I would set ContextMenu in the style of ListBoxItem and not in the DataTemplate :

 <ListBox Name="simpleListBox" ItemsSource="{Binding SimpleList}" DisplayMemberPath="Name"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="ContextMenu"> <Setter.Value> <ContextMenu> ... </ContextMenu> </Setter.Value> </Setter> </Style> </ListBox.ItemContainerStyle> </ListBox> 
+13
source share

All Articles