Search This Blog

Saturday, November 6, 2010

Change Context menu items on the fly

The example using the contextMenuStrip on a winforms form.
Purpose is to use a single contextStripMenu but have the list of menu items change based in the control associated with.

cmsMap = ContextMenuStrip control which is as the contextmenu for tabcontrol1 and drcMapControl1.

void cmsMap_Opening(object sender, CancelEventArgs e)
{
   //Set all visible to all menu items to false
   (sender as ContextMenuStrip).Items["moveTabsToTopToolStripMenuItem"].Visible = false;
   (sender as ContextMenuStrip).Items["moveTabsToBottomToolStripMenuItem"].Visible = false;
   (sender as ContextMenuStrip).Items["addLabelToolStripMenuItem"].Visible = false;

  //Based on the sender.SourceControl make specific menu items visible.
  switch ((sender as ContextMenuStrip).SourceControl.Name)
  {
    case "drcMapControl1":
     (sender as ContextMenuStrip).Items["addLabelToolStripMenuItem"].Visible = true;
        break;
    case "tabControl1":
     (sender as ContextMenuStrip).Items["moveTabsToTopToolStripMenuItem"].Visible = true;
     (sender as ContextMenuStrip).Items["moveTabsToBottomToolStripMenuItem"].Visible = true;
     switch (tabControl1.Alignment)
     {
         case TabAlignment.Bottom:
        (sender as ContextMenuStrip).Items["moveTabsToBottomToolStripMenuItem"].Visible = false;
               break;
         case TabAlignment.Top:
         (sender as ContextMenuStrip).Items["moveTabsToTopToolStripMenuItem"].Visible = false;
                break;
         default:
               break;
    }
        break;
    default:
         break;
    }
}





No comments: