3

首先,我知道这个话题: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 时,上下文菜单会出现并选择整个列表,而不仅仅是一个项目。

是否有一些简单的方法可以识别该项目被点击?谢谢

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

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

1 回答 1

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]);
    }

希望这可以帮助。

于 2013-04-24T10:34:32.773 回答