Back to Devexpress

DxGrid.ContextMenus Property

blazor-devexpress-dot-blazor-dot-dxgrid-d4f5d9f8.md

latest14.9 KB
Original Source

DxGrid.ContextMenus Property

Specifies available context menus.

Namespace : DevExpress.Blazor

Assembly : DevExpress.Blazor.v25.2.dll

NuGet Package : DevExpress.Blazor

Declaration

csharp
[DefaultValue(GridContextMenus.None)]
[Parameter]
public GridContextMenus ContextMenus { get; set; }

Property Value

TypeDefaultDescription
GridContextMenusNone

A collection of GridContextMenus values.

|

Available values:

NameDescription
None

No context menus.

| | Header |

The header context menu.

| | Footer |

The footer context menu.

| | DataRow |

The data row context menu.

| | GroupPanel |

The group panel context menu.

| | GroupRow |

The group row context menu.

| | GroupFooter |

The group footer context menu.

| | All |

All context menus.

|

Remarks

The DevExpress Blazor Grid allows you to display context menus with predefined and custom commands.

Run Demo: Context Menu

Add Context Menus

You can display context menus for the following Grid elements:

Assign GridContextMenus values to the ContextMenus property to display contextual commands when users right-click Grid elements.

Note

  • The Grid does not display a context menu if the menu contains no items.
  • Once you activate a context menu for specific Grid elements, the browser context menu becomes unavailable for the corresponding region (even if the Grid context menu is empty).

The following example demonstrates how to activate/deactivate Grid context menus:

razor
@inject WeatherForecastService ForecastService

<DxGrid Data="@Data" ContextMenus="AvailableContextMenus">
    <Columns>
        <DxGridDataColumn FieldName="Date" DisplayFormat="D" />
        <DxGridDataColumn FieldName="TemperatureC" Caption="@("Temp. (\x2103)")" Width="120px" />
        <DxGridDataColumn FieldName="TemperatureF" Caption="@("Temp. (\x2109)")" Width="120px" />
        <DxGridDataColumn FieldName="Forecast" />
        <DxGridDataColumn FieldName="CloudCover" />
    </Columns>
</DxGrid>

@code {
    object Data { get; set; }
    GridContextMenus AvailableContextMenus;

    protected override void OnInitialized() {
        Data = ForecastService.GetForecast();
        // Activates all context menus (including menus without built-in items)
        AvailableContextMenus = GridContextMenus.All;
        // Disables all context menus
        AvailableContextMenus = GridContextMenus.None;
        // Activates only context menus that contain built-in items
        AvailableContextMenus = GridContextMenus.Header 
                                    | GridContextMenus.GroupPanel | GridContextMenus.GroupRow;
        // Activates menus for all elements except data rows
        AvailableContextMenus = GridContextMenus.All & ~GridContextMenus.DataRow;
    }
}
csharp
using System;

public class WeatherForecast {
    public DateTime Date { get; set; }
    public int TemperatureC { get; set; }
    public double TemperatureF => Math.Round((TemperatureC * 1.8 + 32), 2);
    public string Forecast { get; set; }
    public string CloudCover { get; set; }
    public bool Precipitation { get; set; }
}
csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

public class WeatherForecastService {
private List<WeatherForecast> Forecast { get; set; }

private static string[] CloudCover = new[] {
    "Sunny", "Partly cloudy", "Cloudy", "Storm"
};

Tuple<int, string>[] ConditionsForForecast = new Tuple<int, string>[] {
    Tuple.Create( 22 , "Hot"),
    Tuple.Create( 13 , "Warm"),
    Tuple.Create( 0 , "Cold"),
    Tuple.Create( -10 , "Freezing")
};

public WeatherForecastService() {
    Forecast = CreateForecast();
}

private List<WeatherForecast> CreateForecast() {
    var rng = new Random();
    DateTime startDate = DateTime.Now;
    return Enumerable.Range(1, 15).Select(index => {
        var temperatureC = rng.Next(-10, 30);
        return new WeatherForecast {
            Date = startDate.AddDays(index),               
            TemperatureC = temperatureC,
            CloudCover = CloudCover[rng.Next(0, 4)],
            Precipitation = Convert.ToBoolean(rng.Next(0, 2)),
            Forecast = ConditionsForForecast.First(c => c.Item1 <= temperatureC).Item2
        };
    }).ToList();
}

public IEnumerable<WeatherForecast> GetForecast() {
    return Forecast.ToArray();
}
// ...
}
csharp
// ...
builder.Services.AddSingleton<WeatherForecastService>();

Built-in Items

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

The resulting item 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.

Customization

The CustomizeContextMenu event occurs before a context menu appears. Handle the event to customize the built-in item collection or add custom commands.

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>();

Implements

ContextMenus

See Also

DxGrid Class

DxGrid Members

DevExpress.Blazor Namespace