如何在 UWP 中添加 ListBox 项目上下文菜单

How to add ListBox Item Contextmenu in UWP

我正在搜索以在我的列表框项目的每个项目中添加上下文菜单。我知道在 wp8 应用程序中使用工具包非常容易。但是,uwp 不支持 Toolkit。

如何在 uwp 列表框项目中添加上下文菜单?

谢谢!

您可以创建ListBox.ItemTemplate with MenuFlyout,例如:

<ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid PointerEntered="Grid_PointerEntered" >
                        <FlyoutBase.AttachedFlyout>
                            <MenuFlyout>
                                <MenuFlyoutItem x:Name="EditButton"
                                                            Text="Edit"
                                                            Click="EditButton_Click"/>
                                <MenuFlyoutItem x:Name="DeleteButton"
                                                            Text="Delete"
                                                            Click="DeleteButton_Click"/>
                            </MenuFlyout>
                        </FlyoutBase.AttachedFlyout>
                        <TextBlock Text="{Binding Name}" />
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>

处理 PointerEntered 事件以在指针移入 ListBoxItem 时显示 Flyout:

private void Grid_PointerEntered(object sender, PointerRoutedEventArgs e)
{
            FrameworkElement senderElement = sender as FrameworkElement;
            FlyoutBase flyoutBase = FlyoutBase.GetAttachedFlyout(senderElement);
            flyoutBase.ShowAt(senderElement);
}

处理 MenuFlyoutItem 单击事件:

private void EditButton_Click(object sender, RoutedEventArgs e)
{
            var datacontext = (e.OriginalSource as FrameworkElement).DataContext;

            //this datacontext is probably some object of some type T
}

private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
            var datacontext = (e.OriginalSource as FrameworkElement).DataContext;

            //this datacontext is probably some object of some type T
}

请检查我在Github

上的可行样本