Windows手机中列表的上下文菜单

时间:2013-04-24 08:56:44

标签: windows-phone-7 contextmenu menuitem-selection

首先,我了解这个主题:How to make context menu work for windows phone?

但这种方式太复杂了...... 所以我有这个XAML代码:

 <StackPanel Name="friendsGrid" Margin="0,0,0,0" Background="Transparent"> 
   <ListBox Name="friendsListBox" FontSize="32" Tap="friendsListBox_Tap">
     <toolkit:ContextMenuService.ContextMenu>
     <toolkit:ContextMenu Name="MyContextMenu" Opened="MyContextMenu_Opened">
     <toolkit:MenuItem Header="action" Click="contextMenuAction_Click"/>
     </toolkit:ContextMenu>
     </toolkit:ContextMenuService.ContextMenu>
   </ListBox>
 </StackPanel>

我正在填写这样的列表:

this.friendsListBox.Items.Add(friend.serviceName);

但是,当然,当我执行longtap时,会出现上下文菜单并选择整个List,而不仅仅是一个项目。

是否有一些简单的方法来识别项目被点击? 感谢

顺便说一下,我找到了这个方法,但是contextMenuListItem没有收到任何东西,它仍然是null:

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

1 个答案:

答案 0 :(得分:14)

您应该将ContextMenu块放入ItemTemplate(而不是ListBox块)。 这里是简短的样本 XAML:

            <ListBox Name="TestList" Margin="26,0,26,0" Height="380" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}">
                        <toolkit:ContextMenuService.ContextMenu>
                            <toolkit:ContextMenu Name="ContextMenu" >
                                <toolkit:MenuItem Name="Edit" Header="Edit" Click="Edit_Click"/>
                                <toolkit:MenuItem Name="Delete"  Header="Delete" Click="Delete_Click"/>
                            </toolkit:ContextMenu>
                        </toolkit:ContextMenuService.ContextMenu>
                    </TextBlock>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

代码:

    public List<string> Items = new List<string>
    {
        "Item1",
        "Item2",
        "Item3",
        "Item4",
        "Item5",
    };

    // Constructor
    public MainPage()
    {
        InitializeComponent();
        TestList.ItemsSource = Items;
    }

    private void Edit_Click(object sender, RoutedEventArgs e)
    {
        if (TestList.ItemContainerGenerator == null) return;
        var selectedListBoxItem = TestList.ItemContainerGenerator.ContainerFromItem(((MenuItem) sender).DataContext) as ListBoxItem;
        if (selectedListBoxItem == null) return;
        var selectedIndex = TestList.ItemContainerGenerator.IndexFromContainer(selectedListBoxItem);
        MessageBox.Show(Items[selectedIndex]);
    }

希望这有帮助。