C# 选择RightTapped事件下的ListBoxItem

C# 选择RightTapped事件下的ListBoxItem,c#,uwp,C#,Uwp,我现在有以下事件 private void contactGrid_RightTapped(object sender, RightTappedRoutedEventArgs e) { if (contactGrid.SelectedIndex >= 0) { FrameworkElement senderElement = sender as FrameworkElement; MenuFlyout menu

我现在有以下事件

private void contactGrid_RightTapped(object sender, RightTappedRoutedEventArgs e)
{         

    if (contactGrid.SelectedIndex >= 0)
    {    
        FrameworkElement senderElement = sender as FrameworkElement;

        MenuFlyout menu = new MenuFlyout();
        MenuFlyoutItem item1 = new MenuFlyoutItem() { Text = "Edit Contact" };
        MenuFlyoutItem item2 = new MenuFlyoutItem() { Text = "Comfirm" };
        MenuFlyoutSubItem item2a = new MenuFlyoutSubItem() { Text = "Remove Contact" };

        item1.Click += new RoutedEventHandler(EditContactClicked);
        item2.Click += new RoutedEventHandler(RemoveContactClicked);

        item2a.Items.Add(item2);


        menu.Items.Add(item1);
        menu.Items.Add(item2a);

        menu.ShowAt(senderElement, e.GetPosition(contactGrid));
    }
}
这可以很好地工作,并在列表框项目顶部的鼠标指针处创建右键单击上下文菜单,但前提是首先选择了它。我不明白的是如何让
rightstapped
事件选择右击的项目。我还没有在平板电脑模式和 我目前正在使用鼠标触发右击事件(通过右击)


在平板电脑模式下长按(触发右键点击)是否是默认行为,因此它会选择项目?

据我所知,
contactGrid
是您的
列表框
?我猜您是否有任何类型的
列表
集合
设置为列表框的
项源
?然后,您可以在右击事件中设置
SelectedItem
属性,如下所示:

首先需要修改ItemTemplate,以便RightTapped属于ListBoxItem:

<ListBox x:Name="ContactGrid">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border Background="Transparent" RightTapped="contactGridItem_RightTapped">
                <TextBlock Text="{Binding}" />
            </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

(未经测试,但我会这样解决)

perfect,正是我所需要的。注意,看起来我需要稍微调整代码以适应工作。尤其是
menu.ShowAt(senderElement,例如GetPosition(contactGrid))需要更改为
菜单。ShowAt(发送者作为UIElement,e.GetPosition(发送者作为UIElement))
允许右键单击每次都正确显示,而不是我之前认为的侥幸。
private void contactGridItem_RightTapped(object sender, RightTappedRoutedEventArgs e)
{         
    FrameworkElement senderElement = sender as FrameworkElement;

    // Now you can get the tapped Item from the DataContext and set is as selected
    contactGrid.SelectedItem = senderElement.DataContext;

    if (contactGrid.SelectedIndex >= 0)
    {    

        MenuFlyout menu = new MenuFlyout();
        MenuFlyoutItem item1 = new MenuFlyoutItem() { Text = "Edit Contact" };
        MenuFlyoutItem item2 = new MenuFlyoutItem() { Text = "Comfirm" };
        MenuFlyoutSubItem item2a = new MenuFlyoutSubItem() { Text = "Remove Contact" };

        item1.Click += new RoutedEventHandler(EditContactClicked);
        item2.Click += new RoutedEventHandler(RemoveContactClicked);

        item2a.Items.Add(item2);


        menu.Items.Add(item1);
        menu.Items.Add(item2a);

        menu.ShowAt(senderElement, e.GetPosition(contactGrid));
    }
}