Back to Devexpress

DxContextMenu Class

blazor-devexpress-dot-blazor-b7a7467b.md

latest35.8 KB
Original Source

DxContextMenu Class

A context menu component.

Namespace : DevExpress.Blazor

Assembly : DevExpress.Blazor.v25.2.dll

NuGet Package : DevExpress.Blazor

Declaration

csharp
public class DxContextMenu :
    DxComponentBase,
    IModelWrapper<IContextMenuModel>,
    IDisposable

The following members return DxContextMenu objects:

Remarks

<DxContextMenu> adds a context menu to your Blazor application.

Run Demo: Context Menu

Add a Context Menu to a Project

Follow the steps below to add the Context Menu component to an application:

  1. Create a Blazor Server or Blazor WebAssembly application.

  2. Add the <DxContextMenu></DxContextMenu> markup to a .razor file.

  3. Configure the component: add items, customize their appearance, handle clicks, and so on (see the sections below).

  4. Add code that invokes the context menu when users right-click an HTML element.

API Reference

Refer to the following list for the component API reference: DxContextMenu Members.

Static Render Mode Specifics

Blazor Context Menu does not support static render mode. Enable interactivity to use the component in your application. Refer to the following topic for more details: Enable Interactive Render Mode.

Unbound Mode

In this mode, you should add items to the Context Menu component markup. Use the DxContextMenuBase.Items property to specify a collection of root items. Each item is a DxContextMenuItem class instance that can have a collection of child items (the DxContextMenuItem.Items property).

razor
<DxContextMenu>
    <Items>
        <DxContextMenuItem Text="Font">
            <Items>
                <DxContextMenuItem Text="Times New Roman"></DxContextMenuItem>
                <DxContextMenuItem Text="Tahoma"></DxContextMenuItem>
                <DxContextMenuItem Text="Verdana"></DxContextMenuItem>
            </Items>
        </DxContextMenuItem>
        <DxContextMenuItem Text="Size">
            <Items>
                <DxContextMenuItem Text="8pt"></DxContextMenuItem>
                <DxContextMenuItem Text="10pt"></DxContextMenuItem>
                <DxContextMenuItem Text="12pt"></DxContextMenuItem>
            </Items>
        </DxContextMenuItem>
        <DxContextMenuItem Text="Style">
            <Items>
                <DxContextMenuItem Text="Bold"></DxContextMenuItem>
                <DxContextMenuItem Text="Italic"></DxContextMenuItem>
                <DxContextMenuItem Text="Underline"></DxContextMenuItem>
            </Items>
        </DxContextMenuItem>
        <DxContextMenuItem Text="Clear Formatting" BeginGroup="true"></DxContextMenuItem>
    </Items>
</DxContextMenu>

Customize Items

To specify an item’s name, use the Name property.

The table below lists API members that allow you to customize item appearance.

MemberDescription
TextSpecifies a menu item’s text.
IconCssClassSpecifies the CSS class of a menu item’s icon.
IconUrlSpecifies the URL of a menu item’s icon.

The following code adds items to a menu and specify their icons:

razor
<DxContextMenu>
    <Items>
        <DxContextMenuItem Text="Home" IconCssClass="oi oi-home"></DxContextMenuItem>
        <DxContextMenuItem Text="Contacts" IconCssClass="oi oi-phone"></DxContextMenuItem>
        <DxContextMenuItem Text="Calendar" IconCssClass="oi oi-calendar"></DxContextMenuItem>
    </Items>
</DxContextMenu>

Item Templates

The Context Menu component allows you to use templates to customize the layout and appearance of menu items. You can specify a template for all items or an individual item. Individual templates override common templates.

What to CustomizeCommon TemplatesIndividual Templates
A whole itemDxContextMenu.ItemTemplateDxContextMenuItem.Template
An item’s textDxContextMenu.ItemTextTemplateDxContextMenuItem.TextTemplate
An item’s submenuDxContextMenu.SubMenuTemplateDxContextMenuItem.SubMenuTemplate

The following example defines submenu templates for Text color and Background color menu items:

razor
<div class="demo-preventsel target-container" tabindex="0"
     @oncontextmenu="@OnContextMenu"
     @oncontextmenu:preventDefault
     @onkeydown="@OnKeyDown">
    <p class="d-inline-block text-center m-auto">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris sit amet metus vel nisi blandit tincidunt vel efficitur purus. Nunc nec turpis tempus, accumsan orci auctor, imperdiet mauris. Fusce id purus magna.</p>
</div>

<DxContextMenu @ref="@ContextMenu" PositionTarget="#section-Templates .target-container" SizeMode="Params.SizeMode">
    <Items>
        <DxContextMenuItem Text="Text color">
            <SubMenuTemplate>
                <DxColorPalette Value="@TextColor" ValueChanged="ChangeTextColor">
                    <Groups>
                        <DxColorPaletteGroup Header="Text color" Colors="DxColorPalettePresets.GetPalette(ColorPalettePresetType.Universal)" />
                        <DxColorPaletteGroup Colors="DxColorPalettePresets.GetPalette(ColorPalettePresetType.UniversalGradient)" />
                    </Groups>
                </DxColorPalette>
            </SubMenuTemplate>
        </DxContextMenuItem>
        <DxContextMenuItem Text="Background color">
            <SubMenuTemplate>
                <DxColorPalette Value="@BackgroundColor" ValueChanged="ChangeBackgroundColor">
                    <Groups>
                        <DxColorPaletteGroup Header="Background color" Colors="DxColorPalettePresets.GetPalette(ColorPalettePresetType.Universal)" />
                        <DxColorPaletteGroup Colors="DxColorPalettePresets.GetPalette(ColorPalettePresetType.UniversalGradient)" />
                    </Groups>
                </DxColorPalette>
            </SubMenuTemplate>
        </DxContextMenuItem>
        <DxContextMenuItem Text="Reset colors" Click="@ResetColors" BeginGroup="true"
                           Enabled="@(BackgroundColor != null || TextColor != null)"/>
    </Items>
</DxContextMenu>
csharp
const string UnsetValue = "unset";
DxContextMenu ContextMenu { get; set; }
private string TextColor { get; set; } = null;
private string BackgroundColor { get; set; } = null;

void ChangeTextColor(string color) {
    TextColor = color;
    ContextMenu.HideAsync();
}
void ChangeBackgroundColor(string color) {
    BackgroundColor = color;
    ContextMenu.HideAsync();
}
void ResetColors() {
    BackgroundColor = TextColor = null;
    InvokeAsync(StateHasChanged);
}
async void OnContextMenu(MouseEventArgs args) {
    await ContextMenu.ShowAsync(args);
}
async void OnKeyDown(KeyboardEventArgs args) {
    if (args.Key == "F10" && args.ShiftKey)
        await ContextMenu.ShowAsync(ContextMenuPosition.Center);
}
string GetTextColor() => TextColor == null ? UnsetValue : TextColor;
string GetBackgroudColor() => BackgroundColor == null ? UnsetValue : BackgroundColor;
string GetTextContainerDynamicStyle() => $"color: {GetTextColor()}; background-color: {GetBackgroudColor()};";

Run Demo: Context Menu - Templates

Group Items

You can split context menu items into groups. To specify the start of a new item group, use the BeginGroup property.

razor
<DxContextMenu>
    <Items>
        <DxContextMenuItem Text="Font">
            <Items>
                @* ... *@
            </Items>
        </DxContextMenuItem>
        <DxContextMenuItem Text="Size">
            <Items>
                @* ... *@
            </Items>
        </DxContextMenuItem>
        <DxContextMenuItem Text="Style">
            <Items>
                @* ... *@
            </Items>
        </DxContextMenuItem>
        <DxContextMenuItem Text="Clear Formatting" BeginGroup="true"></DxContextMenuItem>
    </Items>
</DxContextMenu>

A horizontal line separates groups:

Disable User Interaction

To disable a menu item, set its Enabled property to false. The following code snippet disables the Cut and Remove menu items.

razor
<DxContextMenu>
    <Items>
        <DxContextMenuItem Text="Sort By" IconUrl="images/Sort_by.svg">
            <Items>
                @* ... *@
            </Items>
        </DxContextMenuItem>
        <DxContextMenuItem Text="Copy" IconUrl="images/Copy.svg" BeginGroup="true"></DxContextMenuItem>
        <DxContextMenuItem Text="Cut" IconUrl="images/Cut.svg" Enabled="false"></DxContextMenuItem>
        <DxContextMenuItem Text="Remove" IconUrl="images/Clear.svg" Enabled="false"></DxContextMenuItem>
        <DxContextMenuItem Text="Select All" BeginGroup="true"></DxContextMenuItem>
    </Items>
</DxContextMenu>

Bound Mode

You can populate the Context Menu component with items from a data source.

Follow the steps below to bind Context Menu to data:

  1. Use the Data property to specify a data source. You can use different collection types:

  2. Add the DataMappings tag to the component’s markup.

  3. Create the DxContextMenuDataMapping instance and map item properties (BeginGroup, Enabled, and so on) to data source fields. Mappings are used to assign data from the source collection to the component’s data model.

The following code snippet loads context menu items from the TextFormattingMenu class. Each menu item has child items. The code specifies the Children, Text, IconUrl, and BeginGroup mappings to adjust the context menu data model to the specified data source.

razor
<div class="demo-preventsel target-container context-menu-text-container" tabindex="0"
    @oncontextmenu="@OnContextMenu"
    @oncontextmenu:preventDefault
    @onkeydown="@OnKeyDown">
    @* ... *@
</div>
<DxContextMenu PositionTarget="#section-DataBinding .target-container" Data="@MenuItems" ItemClick="@ItemClick" SizeMode="Params.SizeMode" @ref="@ContextMenu">
    <DataMappings>
        <DxContextMenuDataMapping Children="Children"
                                  Text="Text"
                                  IconCssClass="IconCss"
                                  BeginGroup="BeginGroup"
                                  Enabled="Enabled" />
    </DataMappings>
</DxContextMenu>

@code {
    List<TextFormattingMenuItem> menuItems;
    List<TextFormattingMenuItem> MenuItems => menuItems = menuItems ?? TextFormattingMenu.ContextMenuItems(Formatting);
    DxContextMenu ContextMenu { get; set; }
    TextFormatting Formatting { get; set; } = new TextFormatting();

    void ItemClick(ContextMenuItemClickEventArgs args) {
        ((TextFormattingMenuItem)args.ItemInfo.DataItem).Click();
    }
    async void OnContextMenu(MouseEventArgs args) {
        await ContextMenu.ShowAsync(args);
    }
    async void OnKeyDown(KeyboardEventArgs args) {
        if (args.Key == "F10" && args.ShiftKey)
            await ContextMenu.ShowAsync(ContextMenuPosition.Center);
    }
}
csharp
using System.Collections.Generic;
using System.Linq;

namespace BlazorDemo.Data {
    public class TextFormatting {
        public Dictionary<string, bool> Decoration { get; } = new Dictionary<string, bool>() {
            { "Bold", false },
            { "Italic" , false },
            { "Underline" , false },
            { "Strikethrough" , false },
            { "Overline" , false }
        };

        public string FontFamily { get; set; }
        public int FontSize { get; set; }
        public string TextCase { get; set; }
        string GetTextDecoration() {
            string textDecoration = "";
            if(Decoration["Underline"])
                textDecoration += "underline";
            if(Decoration["Overline"])
                textDecoration += " overline";
            if(Decoration["Strikethrough"])
                textDecoration += " line-through";
            return textDecoration;
        }
        public string GetStyleString() {
            string style = "";
            if(!string.IsNullOrEmpty(FontFamily))
                style += $"font-family: {FontFamily}; ";
            if(FontSize > 0)
                style += $"font-size: {FontSize}pt; ";
            if(Decoration["Bold"])
                style += "font-weight: bold; ";
            if(Decoration["Italic"])
                style += "font-style: italic; ";
            if(!string.IsNullOrEmpty(TextCase))
                style += $"text-transform: {TextCase}; ";
            string textDecoration = GetTextDecoration();
            if(!string.IsNullOrEmpty(textDecoration))
                style += $"text-decoration: {textDecoration};";
            return !string.IsNullOrEmpty(style) ? style : null;
        }
        public bool IsStyleChanged() {
            return TextCase != null || FontFamily != null || FontSize != 0 || Decoration.Values.Any(x => x);
        }
        public void ClearFormatting() {
            TextCase = null;
            FontFamily = null;
            FontSize = 0;
            Decoration["Bold"] = false;
            Decoration["Italic"] = false;
            Decoration["Underline"] = false;
            Decoration["Overline"] = false;
            Decoration["Strikethrough"] = false;
        }
    }
}
csharp
using System.Collections.Generic;

namespace BlazorDemo.Data {
    static class TextFormattingMenu {
        public static TextFormattingMenuItem FontFamilyMenuItem(TextFormatting textFormatting) =>
            new TextFormattingParentMenuItem(textFormatting, "Font", new List<TextFormattingMenuItem>() {
                new FontFamilyMenuItem(textFormatting, "Times New Roman", "Times New Roman"),
                new FontFamilyMenuItem(textFormatting, "Tahoma", "Tahoma"),
                new FontFamilyMenuItem(textFormatting, "Verdana", "Verdana"),
                new FontFamilyMenuItem(textFormatting, "Arial", "Arial"),
                new FontFamilyMenuItem(textFormatting, "MS Sans Serif", "MS Sans Serif"),
                new FontFamilyMenuItem(textFormatting, "Courier", "Courier"),
                new FontFamilyMenuItem(textFormatting, "Segoe UI", "Segoe UI"),
                new FontFamilyMenuItem(textFormatting, "Default", null) { BeginGroup = true, IconCss = "menu-icon menu-icon-check" }
            });
        public static TextFormattingMenuItem FontSizeMenuItem(TextFormatting textFormatting) =>
            new TextFormattingParentMenuItem(textFormatting, "Size", new List<TextFormattingMenuItem>() {
                new FontSizeMenuItem(textFormatting, "8pt", 8),
                new FontSizeMenuItem(textFormatting, "10pt", 10),
                new FontSizeMenuItem(textFormatting, "12pt", 12),
                new FontSizeMenuItem(textFormatting, "14pt", 14),
                new FontSizeMenuItem(textFormatting, "18pt", 18),
                new FontSizeMenuItem(textFormatting, "24pt", 24),
                new FontSizeMenuItem(textFormatting, "36pt", 36),
                new FontSizeMenuItem(textFormatting, "Default", 0) { BeginGroup = true }
            });
        static TextFormattingMenuItem FontFormattingMenuItem(TextFormatting textFormatting) =>
            new TextFormattingParentMenuItem(textFormatting, "Style", new List<TextFormattingMenuItem>() {
                new TextDecorationMenuItem(textFormatting, "Bold", "Bold"),
                new TextDecorationMenuItem(textFormatting, "Italic", "Italic"),
                new TextDecorationMenuItem(textFormatting, "Underline", "Underline"),
                new TextDecorationMenuItem(textFormatting, "Overline", "Overline"),
                new TextDecorationMenuItem(textFormatting, "Strikethrough", "Strikethrough")
            });

        public static List<TextFormattingMenuItem> ContextMenuItems(TextFormatting textFormatting) =>
            new List<TextFormattingMenuItem>() {
                FontFamilyMenuItem(textFormatting),
                FontSizeMenuItem(textFormatting),
                FontFormattingMenuItem(textFormatting),
                new ClearFormattingMenuItem(textFormatting) { BeginGroup = true }
            };
            // ...
    }
}

Run Demo: Context Menu - Data Binding

YouTube video

Note

If you bind the Context Menu component with a nonempty Items collection to a data source, unbound data is lost. Bound data overwrites all the items added to the Items collection.

You can also bind the Context Menu component to Grid elements. Refer to the following example for additional information.

YouTube video

Customize Items

To specify an item’s name, use the Name property.

The table below lists API members that allow you to customize item appearance.

MemberDescription
TextSpecifies the text of a navigation component’s item. Map this property to a data source field.
IconCssClassSpecifies the name of a CSS class applied to the icon of the navigation component’s item. Map this property to a data source field.
IconUrlSpecifies the URL of a navigation component’s item icon. Map this property to a data source field.
VisibleSpecifies visibility of the navigation component’s item.

Group Items

You can split context menu items into groups. A horizontal line separates groups:

To specify the start of a new item group, use the BeginGroup property.

razor
<div class="demo-preventsel target-container context-menu-text-container" tabindex="0"
    @oncontextmenu="@OnContextMenu"
    @oncontextmenu:preventDefault
    @onkeydown="@OnKeyDown">
    @* ... *@
</div>
<DxContextMenu PositionTarget="#section-DataBinding .target-container" Data="@MenuItems" ItemClick="@ItemClick" SizeMode="Params.SizeMode" @ref="@ContextMenu">
    <DataMappings>
        <DxContextMenuDataMapping Children="Children"
                                  Text="Text"
                                  IconCssClass="IconCss"
                                  BeginGroup="BeginGroup"
                                  Enabled="Enabled" />
    </DataMappings>
</DxContextMenu>

@code {
    List<TextFormattingMenuItem> menuItems;
    List<TextFormattingMenuItem> MenuItems => menuItems = menuItems ?? TextFormattingMenu.ContextMenuItems(Formatting);
    DxContextMenu ContextMenu { get; set; }
    TextFormatting Formatting { get; set; } = new TextFormatting();

    void ItemClick(ContextMenuItemClickEventArgs args) {
        ((TextFormattingMenuItem)args.ItemInfo.DataItem).Click();
    }
    async void OnContextMenu(MouseEventArgs args) {
        await ContextMenu.ShowAsync(args);
    }
    async void OnKeyDown(KeyboardEventArgs args) {
        if (args.Key == "F10" && args.ShiftKey)
            await ContextMenu.ShowAsync(ContextMenuPosition.Center);
    }
}
csharp
using System.Collections.Generic;
using System.Linq;

namespace BlazorDemo.Data {
    public class TextFormatting {
        public Dictionary<string, bool> Decoration { get; } = new Dictionary<string, bool>() {
            { "Bold", false },
            { "Italic" , false },
            { "Underline" , false },
            { "Strikethrough" , false },
            { "Overline" , false }
        };

        public string FontFamily { get; set; }
        public int FontSize { get; set; }
        public string TextCase { get; set; }
        string GetTextDecoration() {
            string textDecoration = "";
            if(Decoration["Underline"])
                textDecoration += "underline";
            if(Decoration["Overline"])
                textDecoration += " overline";
            if(Decoration["Strikethrough"])
                textDecoration += " line-through";
            return textDecoration;
        }
        public string GetStyleString() {
            string style = "";
            if(!string.IsNullOrEmpty(FontFamily))
                style += $"font-family: {FontFamily}; ";
            if(FontSize > 0)
                style += $"font-size: {FontSize}pt; ";
            if(Decoration["Bold"])
                style += "font-weight: bold; ";
            if(Decoration["Italic"])
                style += "font-style: italic; ";
            if(!string.IsNullOrEmpty(TextCase))
                style += $"text-transform: {TextCase}; ";
            string textDecoration = GetTextDecoration();
            if(!string.IsNullOrEmpty(textDecoration))
                style += $"text-decoration: {textDecoration};";
            return !string.IsNullOrEmpty(style) ? style : null;
        }
        public bool IsStyleChanged() {
            return TextCase != null || FontFamily != null || FontSize != 0 || Decoration.Values.Any(x => x);
        }
        public void ClearFormatting() {
            TextCase = null;
            FontFamily = null;
            FontSize = 0;
            Decoration["Bold"] = false;
            Decoration["Italic"] = false;
            Decoration["Underline"] = false;
            Decoration["Overline"] = false;
            Decoration["Strikethrough"] = false;
        }
    }
}
csharp
using System.Collections.Generic;

namespace BlazorDemo.Data {
    static class TextFormattingMenu {
        public static TextFormattingMenuItem FontFamilyMenuItem(TextFormatting textFormatting) =>
            new TextFormattingParentMenuItem(textFormatting, "Font", new List<TextFormattingMenuItem>() {
                new FontFamilyMenuItem(textFormatting, "Times New Roman", "Times New Roman"),
                new FontFamilyMenuItem(textFormatting, "Tahoma", "Tahoma"),
                new FontFamilyMenuItem(textFormatting, "Verdana", "Verdana"),
                new FontFamilyMenuItem(textFormatting, "Arial", "Arial"),
                new FontFamilyMenuItem(textFormatting, "MS Sans Serif", "MS Sans Serif"),
                new FontFamilyMenuItem(textFormatting, "Courier", "Courier"),
                new FontFamilyMenuItem(textFormatting, "Segoe UI", "Segoe UI"),
                new FontFamilyMenuItem(textFormatting, "Default", null) { BeginGroup = true, IconCss = "menu-icon menu-icon-check" }
            });
        public static TextFormattingMenuItem FontSizeMenuItem(TextFormatting textFormatting) =>
            new TextFormattingParentMenuItem(textFormatting, "Size", new List<TextFormattingMenuItem>() {
                new FontSizeMenuItem(textFormatting, "8pt", 8),
                new FontSizeMenuItem(textFormatting, "10pt", 10),
                new FontSizeMenuItem(textFormatting, "12pt", 12),
                new FontSizeMenuItem(textFormatting, "14pt", 14),
                new FontSizeMenuItem(textFormatting, "18pt", 18),
                new FontSizeMenuItem(textFormatting, "24pt", 24),
                new FontSizeMenuItem(textFormatting, "36pt", 36),
                new FontSizeMenuItem(textFormatting, "Default", 0) { BeginGroup = true }
            });
        static TextFormattingMenuItem FontFormattingMenuItem(TextFormatting textFormatting) =>
            new TextFormattingParentMenuItem(textFormatting, "Style", new List<TextFormattingMenuItem>() {
                new TextDecorationMenuItem(textFormatting, "Bold", "Bold"),
                new TextDecorationMenuItem(textFormatting, "Italic", "Italic"),
                new TextDecorationMenuItem(textFormatting, "Underline", "Underline"),
                new TextDecorationMenuItem(textFormatting, "Overline", "Overline"),
                new TextDecorationMenuItem(textFormatting, "Strikethrough", "Strikethrough")
            });

        public static List<TextFormattingMenuItem> ContextMenuItems(TextFormatting textFormatting) =>
            new List<TextFormattingMenuItem>() {
                FontFamilyMenuItem(textFormatting),
                FontSizeMenuItem(textFormatting),
                FontFormattingMenuItem(textFormatting),
                new ClearFormattingMenuItem(textFormatting) { BeginGroup = true }
            };

        public static List<TextFormattingMenuItem> MenuItems(TextFormatting textFormatting) =>
            new List<TextFormattingMenuItem>() {
                FontFamilyMenuItem(textFormatting),
                FontSizeMenuItem(textFormatting),
                new ClearFormattingMenuItem(textFormatting) { BeginGroup = false }
            };
    }
}

Handle Item Click

The following API members allow you to specify click handlers for context menu items:

MemberDescription
ItemClickSpecifies a common handler for all items.
ClickSpecifies handlers for individual items.

The following code snippet specifies a common click handler for all menu items. When an item is clicked in the menu, the item’s text is displayed in the header.

razor
<div class="card-header">
    @if (ClickedItem != null) {
        <span>Clicked item: <b>@ClickedItem</b></span>
    }
    else {
        <span>Clicked item: None</span>
    }
</div>

<DxContextMenu ItemClick="@OnItemClick">
    <Items>
        <DxContextMenuItem Text="Sort By" IconUrl="images/Sort_by.svg">
            <Items>
                <DxContextMenuItem Text="Name"></DxContextMenuItem>
                <DxContextMenuItem Text="Size"></DxContextMenuItem>
                <DxContextMenuItem Text="Type"></DxContextMenuItem>
            </Items>
        </DxContextMenuItem>
        @* ... *@
    </Items>
</DxContextMenu>

@code {
    string ClickedItem { get; set; }

    void OnItemClick(ContextMenuItemClickEventArgs args) {
        ClickedItem = args.ItemInfo.Text;
    }
}

Show/Hide Context Menu

To display a context menu, handle an event (for example, contextMenu) and call one of the ShowAsync methods:

razor
<div class="h-200"  
     @oncontextmenu="((e) => ContextMenu.ShowAsync(e))" 
     @oncontextmenu:preventDefault>
    <span class="fw-600">RIGHT-CLICK TO SHOW THE CONTEXT MENU</span>
</div>

<DxContextMenu @ref="@ContextMenu">
    <Items>
        <DxContextMenuItem Text="Copy" />
        <DxContextMenuItem Text="Cut" />
        <DxContextMenuItem Text="Remove" />
    </Items>
</DxContextMenu>

@code {
    DxContextMenu ContextMenu { get; set; }
}
css
.h-200 {
    height: 200px;
}
.fw-600 {
    font-weight: 600;
}

You can specify the PositionTarget property to display a context menu at the edge of the target UI element. Refer to the property description for additional information.

The context menu closes when a user clicks outside its boundaries or clicks a menu item that does not have child items. Call the HideAsync() method to close the context menu in code. The following code example demonstrates an ItemClick event handler that closes the menu in response to a click on the SortBy root item:

razor
<DxContextMenu @ref="@ContextMenu" ItemClick="@OnItemClick">
    <Items>
        <DxContextMenuItem Name="SortBy" Text="Sort By">
            <Items>
                <DxContextMenuItem Text="Name"></DxContextMenuItem>
                <DxContextMenuItem Text="Size"></DxContextMenuItem>
                <DxContextMenuItem Text="Type"></DxContextMenuItem>
            </Items>
        </DxContextMenuItem>
    </Items>
</DxContextMenu>

@code {
    DxContextMenu ContextMenu { get; set; }

    void OnItemClick(ContextMenuItemClickEventArgs args) {
        if(args.ItemInfo.Name == "SortBy") {
            ContextMenu.HideAsync();
        }
    }
}

Checked Items

Use the IconUrl or IconCssClass property to implement dynamically checked items.

Run Demo: Context Menu — Data Binding

razor
<DxContextMenu ItemClick="@OnItemClick" >
    <Items>
        <DxContextMenuItem Text="Sort By" IconUrl="/images/sort.svg">
            <Items>
                <DxContextMenuItem Text="Name" IconUrl="@GetChecked("Name")" />
                <DxContextMenuItem Text="Size" IconUrl="@GetChecked("Size")" />
                <DxContextMenuItem Text="Type" IconUrl="@GetChecked("Type")" />
            </Items>
        </DxContextMenuItem>
        <DxContextMenuItem Text="Copy" IconUrl="/images/copy.svg" BeginGroup="true" />
        <DxContextMenuItem Text="Cut" IconUrl="/images/cut.svg" />
        <DxContextMenuItem Text="Remove" IconUrl="/images/clear.svg" />
        <DxContextMenuItem Text="Select All" BeginGroup="true" />
    </Items>
</DxContextMenu>

@code {
    string SortBy { get; set; }

    void OnItemClick(ContextMenuItemClickEventArgs args) {
        if (args.ItemInfo.Text == "Name" || args.ItemInfo.Text == "Size" || args.ItemInfo.Text == "Type")
            SortBy = args.ItemInfo.Text;
    }
    string GetChecked(string ItemText) {
        return (ItemText == SortBy) ? "/images/check.svg" : null;
    }
}

Keyboard Navigation

The DevExpress Blazor Context Menu component supports keyboard shortcuts that allow users to access every UI element and navigate through menu and submenu items. Keyboard navigation is implemented both on the client and server.

Note

Keyboard support allows users to interact with application content in cases they cannot use a mouse or they rely on assistive technologies (like screen readers or switch devices). Refer to the Accessibility help topic for information on other accessibility areas that we address.

The following shortcut keys are available:

Shortcut KeysDescription
Shift + F10, MenuOpens the context menu if the menu’s owner element has focus.
EndMoves focus to the last menu/submenu item.
HomeMoves focus to the first menu/submenu item.
Down ArrowFocuses the first item of the main menu or moves focus to the next menu item.
Up ArrowFocuses the last menu item of the main menu or moves focus to the previous menu item.
Right ArrowFor items with child items: Opens a submenu and moves focus to its first item.
Left ArrowFor main menu items with child items: Opens a submenu and moves focus to its last item.
Left Arrow, EscFor submenu items: Closes the submenu and moves focus to the corresponding parent item.
Enter, SpaceFor items without child items: Invokes a click event handler for the focused menu item and closes the context menu.
For items with child items: Invokes a click event handler for the focused menu item, opens a submenu, and moves focus to its first item. For templated items: Moves focus to the first focusable element within the template.
EscCloses the context menu and returns focus to the menu owner element.
Esc, TabFor templates within menu items: Moves focus to the corresponding menu item.
Tab, Shift + TabCloses the context menu and moves focus to the next or previous focusable page element.

Run Demo: Context Menu

Troubleshooting

If a Blazor application throws unexpected exceptions, refer to the following help topic: Troubleshooting.

Implements

IComponent

IHandleEvent

IHandleAfterRender

IDisposable

Inheritance

Object ComponentBase DxComponentBase DxContextMenu

See Also

DxContextMenu Members

DevExpress.Blazor Namespace