views:

57

answers:

2

I'm trying to add a ContextMenu to items in a ListBox in WPF;

<ListBox.ItemTemplate>
    <DataTemplate>
       <Border>                         
             <Grid>
                <Grid.ContextMenu>
                    <ContextMenu>                                    
                       <MenuItem Header = "Menu item 1"/>
                       <MenuItem Header = "Menu item 2"/>
                       <MenuItem Header = "Menu item 3"/>
                    </ContextMenu>
                </Grid.ContextMenu>
                   ........
                   ........
             </Grid>
         </Border>
       </DataTemplate>
    </ListBox.ItemTemplate>

The problem is that the ContextMenu will only open when clicking on the actual context of the Grid, I want to be able to open the menu by clicking anywhere on the Listbox item.

Should I wrap the Grid in some other control?

+2  A: 

It has been a several months since I've done any solid WPF development (was moved from application development to an actual game team).

From memory, you want to set the ContextMenu property on the Border and then set the Border.Background=Transparent. Setting the background to transparent ensures that it will be participate in the hit detection.

Alternative solution, would be ensure you Grid element stretches horizontally and vertically to fit the container.

...

Also pull the ContextMenu out as a static resource, so that is will be easier to find/edit in the future.

Hope this helps (and my memory does not fail me).

EDIT: I have answered a similar question on StackOverflow previously, please see my answer on WPF: Displaying a Context Menu for a GridView's Items. This answer is more complete as it ensures sets the focus on the ListItem.

Dennis Roche
Great, thanks. Setting Grid.Background=Transparent sorted it
Andronicus
A: 

Add Contextmenu to the ListBox Itself

EDIT

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    >
<Window.Resources>
    <ContextMenu x:Key="contextMenuListBox">
        <MenuItem Header = "Menu item 1"/>
        <MenuItem Header = "Menu item 2"/>
        <MenuItem Header = "Menu item 3"/>
    </ContextMenu>
</Window.Resources>
<Grid>
    <!--<Button Width="100" Content="Show" Click="Button_Click" Height="20"></Button>-->
    <ListBox Name="lstList" Height="100" Width="300" ItemsSource="{Binding}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="Saurabh"  ContextMenu="{StaticResource ResourceKey=contextMenuListBox}">

                </TextBlock>

            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

saurabh
The problem with this is that I want the MenuItems bound to ListBoxItem's DataContext
Andronicus
i have added Modified Code, Please check.
saurabh