Monday, May 06, 2013

windows phone 8 LongListSelector with ContextMenu

* you need to import the Windows Phone Toolkit from NuGet in order to be able to use ContextMenu

in .xaml page you need this:

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

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <phone:LongListSelector x:Name="MainLongListSelector" Margin="0,0,-12,0" >
                <phone:LongListSelector.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Margin="0,0,0,17">
                            <toolkit:ContextMenuService.ContextMenu>
                                <toolkit:ContextMenu Name="ListItemContextMenu" Opened="ListItemContextMenu_Opened" >
                                    <toolkit:MenuItem Name="ContextMenuItemCopy" Header="Copy" Click="MenuItem_Click"/>
                                    <toolkit:MenuItem Name="ContextMenuItemEdit" Header="Edit" Click="MenuItem_Click"/>
                                    <toolkit:MenuItem Name="ContextMenuItemDelete" Header="Delete" Click="MenuItem_Click"/>
                                </toolkit:ContextMenu>
                            </toolkit:ContextMenuService.ContextMenu>
                            <TextBlock Text="{Binding DisplayString}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                        </StackPanel>
                    </DataTemplate>
                </phone:LongListSelector.ItemTemplate>
            </phone:LongListSelector>
        </Grid>


in .xaml.cs you need this

using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

        YourViewModel selectedItem;
        private void ListItemContextMenu_Opened(object sender, RoutedEventArgs e)
        {
            ContextMenu menu = sender as ContextMenu;
            selectedItem = menu.DataContext as YourViewModel;
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem menuItem = sender as MenuItem;
            if (menuItem != null && selectedItem != null)
            {
                switch (menuItem.Name)
                {
                    case "ContextMenuItemCopy":
                        ActionCopy();
                        break;
                    case "ContextMenuItemEdit":
                        ActionEdit();
                        break;
                    case "ContextMenuItemDelete":
                        ActionDelete();
                        break;
                }
            }
        }

No comments: