Windows Phone 7 - ContextMenu and ListBoxes

24 March 2011

The Silverlight Windows Phone Toolkit makes it trivially easy to add a context menu to most Windows Phone 7 controls; all you need to do, really, is add the attached dependency property to the control you want to target with the long-hold gesture, and you're done. So if you're looking to add a context menu for items within a list box, you just need to include it as part of the list item template, as follows:

<ListBox x:Name="MyListBox" ItemsSource="{Binding MyItems}">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <Grid>
                                    <!-- other content of your listitem goes here-->
                                    <toolkit:ContextMenuService.ContextMenu>                                            
                                            <toolkit:ContextMenu Name="MyContextMenu" Opened="MyContextMenu_Opened">                                                
                                                <toolkit:MenuItem Header="action" Click="contextMenuAction_Click"/>
                                            </toolkit:ContextMenu>                                            
                                        </toolkit:ContextMenuService.ContextMenu>
                                </Grid>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>

Note that you'll need to have installed the Silverlight Windows Phone Toolkit, and added the appropriate namespace/reference at the top of your XAML file:

xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

And to find out which ListItem the context menu was raised from, you can use the following code (try it out in Debug mode first to make sure, though!)

ListBoxItem contextMenuListItem = MyListBox.ItemContainerGenerator.ContainerFromItem((sender as ContextMenu).DataContext) as ListBoxItem;

The controls in the Silverlight WP7 toolkit are excellent, and I highly recommend making full use of them.

Tags: context menu, listbox, wp7

Add a Comment

No Comments