如何在 Windows 10 UWP 的 ListView 项目中添加上下文菜单?

How to add context menu in Windows 10 UWP on ListView Item?

我正在开发 Windows 10 UWP 应用程序,在照片应用程序中遇到了一个长按菜单,如下所示

有人可以建议如何在 Windows 10 中创建这种类型的菜单吗?

我检查了 PopupMenu 控件,但它只允许 menu.I 中的 6 个选项想要使用 C# 而不是 XAML 创建此菜单。

您可以使用 Flyout 来达到这个目的,然后在项目的数据模板中,定义对事件的订阅并显示您的菜单。示例可能如下所示:

<ListView>
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid Holding="Grid_Holding" VerticalAlignment="Stretch">
                <FlyoutBase.AttachedFlyout>
                    <MenuFlyout>
                        <MenuFlyoutItem x:Name="EditButton" Text="Edit"/>
                        <MenuFlyoutItem x:Name="DeleteButton" Text="Delete"/>
                        <MenuFlyoutSubItem Text="OtherItems">
                            <MenuFlyoutItem Text="Inside1"/>
                            <MenuFlyoutItem Text="Inside2"/>
                            <MenuFlyoutItem Text="Inside3"/>
                        </MenuFlyoutSubItem>
                    </MenuFlyout>
                </FlyoutBase.AttachedFlyout>
                <TextBlock Text="{Binding}" VerticalAlignment="Center"/>
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
    <x:String>Item 1</x:String>
    <x:String>Item 2</x:String>
    <x:String>Item 3</x:String>
    <x:String>Item 4</x:String>
    <x:String>Item 5</x:String>
</ListView>

后面的代码:

private void Grid_Holding(object sender, HoldingRoutedEventArgs e)
{
    FrameworkElement senderElement = sender as FrameworkElement;
    // If you need the clicked element:
    // Item whichOne = senderElement.DataContext as Item;
    FlyoutBase flyoutBase = FlyoutBase.GetAttachedFlyout(senderElement);
    flyoutBase.ShowAt(senderElement);
}

因此,您应该会看到如下图所示的内容。

您还可以找到更多帮助 at MSDN


评论后编辑。

通常,您在 XAML 中创建的所有内容都可以在代码隐藏中创建。如果你想创建一个 Flyout,那么它可以是这样的:

private bool startedHolding = false;
private void Grid_Holding(object sender, HoldingRoutedEventArgs e)
{
    // simple checkup for holding release for this sample, though this probalby need better handling
    startedHolding = !startedHolding;
    if (startedHolding)
    {
        MenuFlyout myFlyout = new MenuFlyout();
        MenuFlyoutItem firstItem = new MenuFlyoutItem { Text = "First item" };
        MenuFlyoutItem secondItem = new MenuFlyoutItem { Text = "Second item" };
        MenuFlyoutSubItem subItem = new MenuFlyoutSubItem { Text = "Other items" };
        MenuFlyoutItem item1 = new MenuFlyoutItem { Text = "First sub item" };
        MenuFlyoutItem item2 = new MenuFlyoutItem { Text = "Second sub item" };
        subItem.Items.Add(item1);
        subItem.Items.Add(item2);
        myFlyout.Items.Add(firstItem);
        myFlyout.Items.Add(secondItem);
        myFlyout.Items.Add(subItem);
        FrameworkElement senderElement = sender as FrameworkElement;
        myFlyout.ShowAt(senderElement);
    }
}