ContextMenuStrip创建主菜单与子菜单
using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Data;
namespace MenuStripExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//给控件添加Opening事件
this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.ContextMenu1_Popup);
//给具体哪个控件添加菜单显示(这里给到整个窗体)
this.ContextMenuStrip = contextMenuStrip1;
}
private void Form1_Load(object sender, EventArgs e)
{
//创建菜单
CreateMenu();
}
//主菜单
protected ToolStripItem[] _menuItem;
//子菜单(Two)
private ToolStripItem[] _subMenuTwo;
/// <summary>
/// 菜单枚举
/// </summary>
private enum MenuIndex
{
One = 0,
Two = 2
}
/// <summary>
/// 创建菜单
/// </summary>
protected virtual void CreateMenu()
{
_menuItem = new ToolStripItem[]
{
new ToolStripMenuItem("One",null,Sumu_Click)
, new ToolStripSeparator()
, new ToolStripMenuItem("Two", null, _subMenuTwo)
};
}
private void ContextMenu1_Popup(object sender, CancelEventArgs e)
{
//判断是否有Two这个菜单项
if (_menuItem.Where(x => x.Text == "Two").Any())
{
//如果子菜单(_subMenuTwo)没有值时取值
if (_subMenuTwo == null || !_subMenuTwo.Any())
{
//从数据库拿子菜单
//DataTable dt = new DataTable();
//ToolStripItem[] tsArr = new ToolStripItem[dt.Rows.Count];
//int count = 0;
//foreach (DataRow dr in dt.Rows)
//{
// tsArr[count] = new ToolStripMenuItem(string.Concat(dr["数据1"], "-", dr["数据2"].ToString()), null, Sumu_Click);
// count += 1;
//}
//_subMenuTwo = tsArr;
ToolStripItem[] tsArr = new ToolStripItem[1];
tsArr[0] = new ToolStripMenuItem(string.Concat("Two", "-", "One").ToString(), null, Sumu_Click);
_subMenuTwo = tsArr;
var menu = (ToolStripMenuItem)MainMenu(MenuIndex.Two);
menu.DropDownItems.Clear();
menu.DropDownItems.AddRange(_subMenuTwo);
}
}
//整体更新到控件
{
var withBlock = contextMenuStrip1.Items;
withBlock.Clear();
withBlock.AddRange(_menuItem);
}
}
/// <summary>
/// 返回对应下标菜单
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
private ToolStripItem MainMenu(MenuIndex index)
{
return _menuItem[(int)index];
}
/// <summary>
/// 菜单点击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Sumu_Click(object sender, EventArgs e)
{
string text = ((ToolStripMenuItem)sender).Text;
MessageBox.Show("Sumu_Click:" + $"{text}", "SUMU", MessageBoxButtons.OKCancel);
}
}
}
效果图如下: