Context Menu Integration
In some cases, you may need to know which element the user clicked so you can use it in the command handling. You may also want to adjust the menu contents based on which element the user clicked (e.g., disable or entirely remove some items from the menu based on a condition).
Using the Selector parameter to attach the context menu to one or more targets at a time is simple, and can be useful when you want the same menu for many elements, but it does not matter which one the user clicked. So, the Telerik Context Menu offers the ShowAsync(x, y) method that lets you show it on demand after executing business logic.
To achieve such flexibility and granularity, you can:
- Use your own code to hook to an event such as
@oncontextmenuto store the desired target and its metadata. You can use other events such as@onclicktoo.- You can use other events to show the context menu, like click, mousedown and so on. Make sure to pass correct coordinates to the menu - they must be relative to the viewport.
- If you use the
@oncontextmenuevent, also add@oncontextmenu:preventDefault="true"to avoid the browser context menu which will always show above HTML structures on the page, like the Telerik Context Menu.
- Optionally, alter the data source or templates of the menu based on the metadata for the target.
- Show the Telerik menu through its
@refand theShowAsyncmethod it exposes.
This article provides the following two examples:
You can apply the approach of hooking to your own events to show the context menu in other scenarios as well. For example, you can add a context menu for your treeview nodes.
Know The Target And Adjust Items
Hooking to your own HTML elements' events lets you determine what to do with the context menu before showing it (for example, altering its data source).
Use the context menu target and change menu items based on the target data
Context Menu for a Grid Row
To integrate the context menu with the Telerik Grid, you need to:
- Use the grid's
OnRowContextMenuevent to get the current row model and show the menu - Use the context menu's
OnClickevent to handle the desired operation
In this example, the context menu is used to select/deselect items, put an item in edit mode and delete items
Use a Context Menu for Grid rows
Context Menu for a TreeView Node
To integrate the ContextMenu with the TreeView, you need to:
- Use the
OnItemContextMenuevent of the TreeView to get the current row model and show the menu - Use the context menu's
OnClickevent to handle the desired operation
In this example, the context menu is used to select/deselect items and delete items
Use a Context Menu for TreeView nodes