C#: Listbox Contextmenu for Listboxitems (WPF)

user437899 picture user437899 · Dec 11, 2010 · Viewed 14.1k times · Source

i want for my Listbox in WPF a contextmenu. I did it with a contextmenu for the whole listbox, but you can richt-click to get the contextmenu even if you don't click on a item.

I found something at google, but this didn't work out.

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 textblock like in the example, with other elements like in other tutorials, i tired it without and many other things- but nothing worked. No contextmenu for my listbox items :(

later i tried something like this:

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

But it didn't work too.

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

thank you

Answer

Thomas Levesque picture Thomas Levesque · Dec 12, 2010

I would set the ContextMenu in the ListBoxItem's style, rather than 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>