How to determine which list items trigger the Context menu in a Blazor ListBox
In a Blazor application, you may want to identify which list items in a ListBox trigger the opening of a context menu. This can be achieved by utilizing the HtmlAttributes property of ListBoxFieldSettings to assign unique IDs to each list item. Additionally, the Opened event of the context menu can be used to capture the ID of the list item that was interacted with.
The SfListBox component is configured with a data source and event handlers, using HtmlAttributes property to assign unique IDs. The SfContextMenu, linked to the ListBox, provides options like “Add Column” and “Delete Column.” The Opened event identifies the selected list item via args.TargetId and retrieves its data using the GetDataByValue method.
Below is a code snippet demonstrating how to implement the above steps:
<SfListBox id="target" @ref="@ListboxObj" CssClass="e-listbox" TValue="string[]" DataSource="@FormItems" TItem="FormItem" AllowDragAndDrop="true">
<ListBoxEvents TValue="string[]" ValueChange="ItemChanged" TItem="FormItem"></ListBoxEvents>
<ListBoxFieldSettings Text="Field" Value="FormItemNo" HtmlAttributes="attributes" />
<SfContextMenu Target="#target" TValue="MenuItem">
<MenuItems>
<MenuItem Text="Add column"></MenuItem>
<MenuItem Text="Delete column"></MenuItem>
</MenuItems>
<MenuEvents TValue="MenuItem" ItemSelected="@selectedHandler" Opened="open"></MenuEvents>
</SfContextMenu>
</SfListBox>
@code {
private List<FormItem> FormItems = new List<FormItem>
{
new FormItem { Field = "Field1", FormItemNo = "1", attributes = new Dictionary<string, object>() {{ "id", "1" }}},
new FormItem { Field = "Field2", FormItemNo = "2", attributes = new Dictionary<string, object>() {{ "id", "2" }} },
new FormItem { Field = "Field3", FormItemNo = "3", attributes = new Dictionary<string, object>() {{ "id", "3" }} },
};
private void open(OpenCloseMenuEventArgs<MenuItem> args)
{
selectedList = ListboxObj.GetDataByValue(new string[] { args.TargetId });
}
}
Sample: https://blazorplayground.syncfusion.com/LjrfirVQBQllTACK