New to Telerik UI for WinForms? Download free 30-day trial

Distinguishing the Source Control of RadContextMenu

Environment

Product Version 2018.1 220
Product RadContextMenu for WinForms

Description

The RadContextMenuManager component allows a single RadContextMenu instance to be associated with various controls. This KB article demonstrates a way to distinguish the source control of the menu. It may be useful in a scenario requiring the menu items need to be dynamically changed or different actions be invoked upon clicking the menu items. The example assumes that two different RadListView controls are using the same RadContextMenu. Additional information about the RadContextMenuManager component is available here: https://docs.telerik.com/devtools/winforms/menus/contextmenu/assign-radcontextmenu-to-telerik-and-non-telerik-controls.

Solution

The source control will be extracted from the element`s visual tree and stored in a variable so that it can be validated upon clicking the menu items.

Figure 1: Single Context Menu

distinguishing-the-source-control-of-radcontextmenu 001

Context Menu Events

public partial class RadContextMenuSourceControlForm : Telerik.WinControls.UI.RadForm
{
    public RadContextMenuSourceControlForm()
    {
        InitializeComponent();
        this.radContextMenu1.DropDownOpening += RadContextMenu1_DropDownOpening;
        this.radMenuItem1.Click += RadMenuItem1_Click;
    }
    private void RadMenuItem1_Click(object sender, EventArgs e)
    {
        if (this.currentControl == this.radListView1)
        {
            //...
        }
        else if (this.currentControl == this.radListView2)
        {
            //...
        }
        RadMessageBox.Show(this.currentControl.Name);
    }
    RadControl currentControl = null;
    private void RadContextMenu1_DropDownOpening(object sender, CancelEventArgs e)
    {
        RadElement element = sender as RadElement;
        if (element == null)
        {
            return;
        }
        this.currentControl = element.ElementTree.Control as RadControl;
        if (this.currentControl != null)
        {
            Console.WriteLine(this.currentControl.Name);
        }
    }
}