Skip to content

Context Menus

Vetle444 edited this page May 30, 2024 · 6 revisions

A context menu is a pop-up menu that provides shortcuts for actions related to the tapped item.

Inspiration

Usage

A context menu can be attached to any Element. In this example a context menu is attached to a Button with one ContextMenuItem. The ItemClickedCommand is bound to a Command, thus, when any item is tapped, the Command will be executed.

 <dui:Button Text="Open context menu">
    <dui:ContextMenuEffect.Menu>
        <dui:ContextMenu ItemClickedCommand="{Binding ItemClickedCommand}">
            <dui:ContextMenuItem Title="Tap me" />
        </dui:ContextMenu>
    </dui:ContextMenuEffect.Menu> 
</dui:Button>

Modes

There are two context menu-modes:

  • Pressed (default)
  • LongPressed

Pressed

This mode requires people to tap to show a context menu.

 <dui:Button Text="Open context menu" dui:ContextMenuEffect.Mode="Pressed">
    <dui:ContextMenuEffect.Menu>
        ...
    </dui:ContextMenuEffect.Menu> 
</dui:Button>

LongPressed

This mode requires people to long-tap the Element to show the context menu.

On iOS a "preview" of the Element will be displayed.

 <dui:Button Text="Open context menu" dui:ContextMenuEffect.Mode="LongPressed">
    <dui:ContextMenuEffect.Menu>
        ...
    </dui:ContextMenuEffect.Menu> 
</dui:Button>

Global Callbacks

Click events on ContextMenuItems can be subscribed to inside UseDIPSUI() in MauiProgram.cs:

...
var builder = MauiApp.CreateBuilder();
builder
    .UseMauiApp<App>()
    .UseDIPSUI(options =>
    {
       options.SetContextMenuItemClickedCallback(OnContextMenuItemClicked);
    });
...

private static void OnContextMenuItemClicked(ContextMenuItem item)
{
    Console.WriteLine($"Clicked context menu item with title {item.Title}!");
}
...

Attaching a Context Menu to a ToolbarItem

To attach a Context Menu to a ToolbarItem we have created a ContextMenuToolbarItem, which has a ContextMenu property.

Usage

<dui:ContentPage.ToolbarItems>
    <dui:ContextMenuToolbarItem Text="Tap">
        <dui:ContextMenuToolbarItem.ContextMenu>
            <dui:ContextMenu Title="Context menu">
                <dui:ContextMenuItem Title="Item 1" />
            </dui:ContextMenu>
        </dui:ContextMenuToolbarItem.ContextMenu>
    </dui:ContextMenuToolbarItem>
</dui:ContentPage.ToolbarItems>

NB! Attaching a Context Menu on a ToolbarItem is only supported when the Application is run on Shell.

Known Limitations

  • Long-Pressed Mode are not supported (yet) on ToolbarItems

Properties

Inspect the components properties class to further customize and use it.

Clone this wiki locally