Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing a ContextMenu

I'm having difficulty finding good documentation for this, despite searching for a while.

I'd like to have a context menu in my app that replicates the behavior seen with other tap-and-hold context menus, like pinning an app to the start screen from the app list.

Here is my Context menu:

                <toolkit:ContextMenuService.ContextMenu>
                    <toolkit:ContextMenu x:Name="sectionContextMenu">
                        <toolkit:MenuItem Header="Hide this section from this list" />
                    </toolkit:ContextMenu>
                </toolkit:ContextMenuService.ContextMenu>

How do I make it show?

like image 707
Nick Heiner Avatar asked Jan 21 '23 21:01

Nick Heiner


2 Answers

The context menu needs to be attached to the element that you want the user to tap and hold.

<Border Margin="0,12" BorderBrush="{StaticResource PhoneForegroundBrush}" BorderThickness="2" Background="Transparent" VerticalAlignment="Center" Padding="16">
   <toolkit:ContextMenuService.ContextMenu>
      <toolkit:ContextMenu x:Name="sectionContextMenu">
         <toolkit:MenuItem Header="Hide this section from this list" />
      </toolkit:ContextMenu>
   </toolkit:ContextMenuService.ContextMenu>
   <TextBlock Text="Tap and hold here to invoke a ContextMenu" Style="{StaticResource PhoneTextNormalStyle}"/>
</Border>

The user can now invoke the context menu with a tap and hold on the content of this Border element.

like image 102
AnthonyWJones Avatar answered Jan 29 '23 01:01

AnthonyWJones


Unique context menu for different items depending on the content.

private ContextMenu CreateContextMenu(ListBoxItem lbi)
{
    ContextMenu contextMenu = new ContextMenu();
    ContextMenuService.SetContextMenu(lbi, contextMenu);
    contextMenu.Padding = new Thickness(0);

    string item_1 = "item 1";
    if(lbi.Content is string) {
        item_1 = lbi.Content as string;
    }
    contextMenu.ItemsSource = new List<string> { item_1, "item 2", "item 3" };
    contextMenu.IsOpen = true;
    return contextMenu;
}

private void Results_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (Results.SelectedIndex == -1) return;
    int index = Results.SelectedIndex;

    ListBoxItem lbi = Results.ItemContainerGenerator.ContainerFromIndex(index) as ListBoxItem;

    CreateContextMenu(lbi);
    Results.SelectedIndex = -1;
}
like image 37
Dmitry Avatar answered Jan 29 '23 01:01

Dmitry