Back to Devexpress

DxGrid.CustomizeContextMenu Event

blazor-devexpress-dot-blazor-dot-dxgrid-21aff5bc.md

latest18.8 KB
Original Source

DxGrid.CustomizeContextMenu Event

Allows you to customize context menus.

Namespace : DevExpress.Blazor

Assembly : DevExpress.Blazor.v25.2.dll

NuGet Package : DevExpress.Blazor

Declaration

csharp
[Parameter]
public Action<GridCustomizeContextMenuEventArgs> CustomizeContextMenu { get; set; }

Parameters

TypeDescription
GridCustomizeContextMenuEventArgs

An object that contains data for this event.

|

Remarks

The DevExpress Blazor Grid allows you to display context menus with predefined and custom commands. Use the ContextMenus property to activate context menus for specific Grid elements. Handle the CustomizeContextMenu event to modify the menu item collection.

Run Demo: Context Menu

Identify Target Cells

Use the Context event argument to identify the target Grid element and obtain contextual information.

Target ElementContext TypeContextual information
AnyGridCommandContextGrid
Data RowGridDataRowCommandContextGrid, Column, DataItem, RowVisibleIndex
FooterGridFooterCommandContextGrid, Column, SummaryItems
Group FooterGridGroupFooterCommandContextGrid, Column, GroupRowVisibleIndex, SummaryItems
Group PanelGridGroupPanelCommandContextGrid
Group RowGridGroupRowCommandContextGrid, GroupColumn, RowVisibleIndex
HeaderGridHeaderCommandContextGrid, Column

The following code snippet customizes commands available in the header context menu:

razor
@inject NwindDataService NwindDataService

<DxGrid Data="Data"
        ShowGroupPanel="true"
        ContextMenus="@(GridContextMenus.Header)"
        CustomizeContextMenu="CustomizeContextMenu">
    <Columns>
        <DxGridSelectionColumn />
        <DxGridDataColumn FieldName="City" />
        <DxGridDataColumn FieldName="Country" />
        <DxGridDataColumn FieldName="CustomerName" GroupIndex="0" />
        <DxGridDataColumn FieldName="ProductName" />
        <DxGridDataColumn FieldName="Total"
                          UnboundType="GridUnboundColumnType.Decimal"
                          UnboundExpression="[UnitPrice] * [Quantity]"
                          DisplayFormat="c"
                          MinWidth="100" />
    </Columns>
</DxGrid>

@code {
    BindingList<Invoice> Data { get; set; }

    void CustomizeContextMenu(GridCustomizeContextMenuEventArgs args) {
        if (args.Context is GridHeaderCommandContext headerContext) {
            // Customizes context menu commands for the Total column header
            if (headerContext.Column is IGridDataColumn dataColumn && dataColumn.FieldName == "Total") {
                args.Items.Remove(GridContextMenuDefaultItemNames.GroupByColumn);
                args.Items.Remove(GridContextMenuDefaultItemNames.UngroupColumn);
            }
            // Customizes context menu commands for the selection column header
            if (headerContext.Column is IGridSelectionColumn selectionColumn) {
                var isFixed = selectionColumn.FixedPosition != GridColumnFixedPosition.None;
                string itemText = isFixed ? "Unfix Column" : "Fix Column to the Left";
                var newValue = isFixed ? GridColumnFixedPosition.None : GridColumnFixedPosition.Left;

                args.Items.AddCustomItem(itemText, () => {
                    headerContext.Grid.BeginUpdate();
                    headerContext.Column.FixedPosition = newValue;
                    headerContext.Grid.EndUpdate();
                });
            }
        }
    }

    protected override async Task OnInitializedAsync() {
        var invoices = await NwindDataService.GetInvoicesAsync();
        Data = new BindingList<Invoice>(invoices.ToList());
    }
}
csharp
public class Invoice {
    public string ShipName { get; set; }
    public string ShipAddress { get; set; }
    public string ShipCity { get; set; }
    public string ShipRegion { get; set; }
    public string ShipPostalCode { get; set; }
    public string ShipCountry { get; set; }
    public string CustomerId { get; set; }
    public string CustomerName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Region { get; set; }
    public string PostalCode { get; set; }
    public string Country { get; set; }
    public string Salesperson { get; set; }
    public int OrderId { get; set; }
    public DateTime? OrderDate { get; set; }
    public DateTime? RequiredDate { get; set; }
    public DateTime? ShippedDate { get; set; }
    public string ShipperName { get; set; }
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public decimal UnitPrice { get; set; }
    public short Quantity { get; set; }
    public float Discount { get; set; }
    public decimal? ExtendedPrice { get; set; }
    public decimal? Freight { get; set; }
}
csharp
public partial class NwindDataService {
    public Task<IEnumerable<Product>> GetProductsAsync(CancellationToken ct = default) {
        // Return your data here
    }
}
csharp
services.AddScoped<NwindDataService>();

Built-in Commands

The table below lists context menu types and built-in commands available in the Grid:

- The context menu includes this item by default.
- You can add this item to the context menu.
- The context menu does not support this item.

Menu ItemData RowFooterGroup FooterGroup PanelGroup RowHeader
AutoFitAll
ClearColumnSorting
ClearGrouping
CollapseAll
ExpandAll
GroupByColumn
HideColumn
HideGroupPanel
ShowColumnChooser
ShowFilterBuilder
ShowGroupPanel
SortColumnAscending
SortColumnDescending
UngroupColumn

Access Items

The Items event argument contains an initial item collection. This collection depends on the menu type, Grid settings, and component state. For instance, a header context menu contains the SortColumnAscending command only if sorting is allowed (on both Grid and column levels). The ClearColumnSorting command is disabled if the target column is not sorted.

Call a Contains method overload to check whether the context menu includes a particular item. Obtain an item by its name or index:

csharp
void CustomizeContextMenu(GridCustomizeContextMenuEventArgs args) {    
    // Returns the first item
    IContextMenuItem firstItem = args.Items[0];
    // Returns the "Auto Fit All" item
    IContextMenuItem autoFitItem;
    if (args.Items.Contains(GridContextMenuDefaultItemNames.AutoFitAll))
        autoFitItem = args.Items[GridContextMenuDefaultItemNames.AutoFitAll];
}

Add Items

Add Built-In Items

The GridContextMenuDefaultItemNames class contains names of all built-in items. Pass an item name to an Add method overload to add this item to the context menu. Refer to the following section for a list of predefined items: Built-in Commands.

Note

The Grid validates item collections for each context menu type and hides unsupported commands (even if you add these commands in the CustomizeContextMenu event handler).

csharp
void CustomizeContextMenu(GridCustomizeContextMenuEventArgs args) {  
      // Inserts the "Auto Fit All" item at the end of the item collection
      args.Items.Add(GridContextMenuDefaultItemNames.AutoFitAll);
      // Inserts the "Show Column Chooser" item at the first position in the item collection
      args.Items.Add(0, GridContextMenuDefaultItemNames.ShowColumnChooser);
}

Add Custom Items

AddCustomItem method overloads allow you to create a custom item and add it to the item collection:

csharp
void CustomizeContextMenu(GridCustomizeContextMenuEventArgs args) {
    // Inserts a custom item at the first position in the item collection
    var isFooterVisible = args.Grid.FooterDisplayMode != GridFooterDisplayMode.Never;
    string footerItemText = isFooterVisible ? "Hide Footer" : "Show Footer";
    var newState = isFooterVisible ? GridFooterDisplayMode.Never : GridFooterDisplayMode.Always;
    args.Items.AddCustomItem(0, footerItemText, () => {
        args.Grid.BeginUpdate();
        args.Grid.FooterDisplayMode = newState;
        args.Grid.EndUpdate();
    });
    // Inserts a custom item at the end of the item collection
    if (args.Context is GridHeaderCommandContext headerContext) {
        if (headerContext.Column is IGridCommandColumn commandColumn) {
            var isFixed = commandColumn.FixedPosition != GridColumnFixedPosition.None;
            string fixedItemText = isFixed ? "Unfix Column" : "Fix Column to the Left";
            var newValue = isFixed ? GridColumnFixedPosition.None : GridColumnFixedPosition.Left;
            args.Items.AddCustomItem(fixedItemText, () => {
                headerContext.Grid.BeginUpdate();
                headerContext.Column.FixedPosition = newValue;
                headerContext.Grid.EndUpdate();
            });
        }
    }
}

Add Nested Items

Built-in context menu commands do not have nested items. Use a command’s Items property to add nested menu items:

csharp
void CustomizeContextMenu(GridCustomizeContextMenuEventArgs args) {  
    if (args.Context is GridHeaderCommandContext headerContext) {
        // Inserts a custom item at the first position in the item collection
        var sortItem = args.Items.AddCustomItem(0, "Sort...");
        // Adds default items to the item collection of the inserted item
        sortItem.Items.Add(GridContextMenuDefaultItemNames.SortColumnAscending);
        sortItem.Items.Add(GridContextMenuDefaultItemNames.SortColumnDescending);
        sortItem.Items.Add(GridContextMenuDefaultItemNames.ClearColumnSorting);
    }
}

Remove Items

Remove method overloads allow you to remove an item with the specified name or index from the item collection. To remove all items from the collection, call the Clear() method.

csharp
void CustomizeContextMenu(GridCustomizeContextMenuEventArgs args) {  
    // Removes the first item
    args.Items.Remove(0);
    // Removes the "Show Column Chooser" item
    args.Items.Remove(GridContextMenuDefaultItemNames.ShowColumnChooser);
    // Removes all items
    args.Items.Clear();
}

Customize Items

Access an item and use its properties to customize command availability, appearance, and behavior.

csharp
void CustomizeContextMenu(GridCustomizeContextMenuEventArgs args) {
    // Hides icons for all built-in commands
    foreach(var item in args.Items)
        item.IconUrl = string.Empty;   
    if (args.Context is GridHeaderCommandContext headerContext) {
        // Removes the "Sort Column Descending" item
        args.Items.Remove(GridContextMenuDefaultItemNames.SortColumnDescending);
        // Changes the "Sort Column Ascending" item caption
        args.Items[GridContextMenuDefaultItemNames.SortColumnAscending].Text = "Sort";
        // Adds and configures a custom command for the command column header
        if (headerContext.Column is IGridCommandColumn commandColumn) {
            var isFixed = commandColumn.FixedPosition != GridColumnFixedPosition.None;
            string itemText = isFixed ? "Unfix Column" : "Fix Column to the Left";
            var newValue = isFixed ? GridColumnFixedPosition.None : GridColumnFixedPosition.Left;

            var fixColumnItem = args.Items.AddCustomItem(itemText, () => {
                headerContext.Grid.BeginUpdate();
                headerContext.Column.FixedPosition = newValue;
                headerContext.Grid.EndUpdate();
            });
            fixColumnItem.BeginGroup = true;
        }
    }
}

See Also

DxGrid Class

DxGrid Members

DevExpress.Blazor Namespace