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

时间:2016-06-06 11:57:34

标签: c# uwp windows-10-universal

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

ContextMenu

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

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

1 个答案:

答案 0 :(得分:9)

您可以使用Flyout来实现此目的,然后在项目的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>

背后的代码:

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

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

enter image description here

更多帮助您还可以找到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);
    }
}