如何在UWP中添加ListBox项Contextmenu

时间:2015-10-10 07:15:13

标签: windows-10 win-universal-app uwp windows-10-mobile

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

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

谢谢!

1 个答案:

答案 0 :(得分:6)

您可以使用ListBox.ItemTemplate创建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>

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

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

处理MenuFlyoutItem Click事件:

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

上查看我的可行样本