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

Kin*_*sar 2 c# uwp windows-10-universal

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

上下文菜单

有人可以建议如何在Windows 10中创建此类菜单吗?

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

Rom*_*asz 9

您可以将Flyout用于此目的,然后在item的datatemplate中,定义订阅事件并显示您的菜单.示例可能如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

而背后的代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

您还可以在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);
    }
}
Run Code Online (Sandbox Code Playgroud)