Search code examples
windows-10win-universal-appuwpwindows-10-mobile

How to add ListBox Item Contextmenu in UWP


I am searching to add Context menu in every item of my listbox item. I know it was very easy in wp8 app using toolkit. However, Toolkit is not supported in uwp.

How can I add Context menu in uwp listbox item?

Thanks!


Solution

  • You can create ListBox.ItemTemplate with MenuFlyout, for example:

    <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>
    

    Handle the PointerEntered event to show Flyout when the pointer has been moved into an ListBoxItem:

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

    Handle MenuFlyoutItem Click event:

    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
    }
    

    Please check my feasible sample on Github