如何在UWP中添加ListBox项Contextmenu

ARH*_*ARH 3 win-universal-app windows-10 windows-10-mobile uwp

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

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

谢谢!

Fra*_*SFT 7

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

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

当指针移动到ListBoxItem时,处理PointerEntered事件以显示Flyout:

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

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

请在Github上查看我的可行样本

  • @ARH我在Windows10上测试过,右键点击效果很好 (3认同)