private void Form2_Load(object sender, EventArgs e)
{
CreateMenu();
}
private void CreateMenu()
{
//定义菜单条
Bar bar = new Bar("Menu Bar");
bar.MenuBar = true;
bar.Stretch = true;
bar.Style = eDotNetBarStyle.Office2003;
dotNetBarManager1.Bars.Add(bar); //添加到dotNetBarManager1对象
bar.DockSide = eDockSide.Top; //设置Dock样式
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start(); // 开始监视代码运行时间
var listMenu = GetButtonItem(0);
listMenu.ToList().ForEach(x => bar.Items.Add(x));
bar.RecalcLayout(); //重绘布局
stopwatch.Stop(); // 停止监视
TimeSpan timespan = stopwatch.Elapsed; // 获取当前实例测量得出的总时间
this.labelX1.Text = "生成菜单耗时" + timespan.TotalSeconds.ToString() + "毫秒";
//textBoxX1.LostFocus += (s, e) => { MessageBox.Show("失去焦点"); };
}
public class JsonTuple<T1, T2>
{
public T1 Item1 { get; set; }
public T2 Item2 { get; set; }
public KeyValuePair<Int32, Int32> KvType { get; set; }
public Boolean Tag { get; set; }
public JsonTuple(T1 item1, T2 item2, KeyValuePair<Int32, Int32> kvType, bool tag)
{
this.Item1 = item1;
this.Item2 = item2;
this.KvType = kvType;
this.Tag = tag;
}
public JsonTuple(T1 item1, T2 item2, bool tag)
: this(item1, item2, new KeyValuePair<int, int>(0, 0), tag)
{
}
}
private List<JsonTuple<string, string>> GetMenuSetter()
{
List<JsonTuple<string, string>> listMenu = new List<JsonTuple<string, string>>
{
//有&会在字体下面显示下划线
new JsonTuple<string,string>("bFile","&File",new KeyValuePair<int, int>(1,0),false),
new JsonTuple<string,string>("bOpen","Open",new KeyValuePair<int, int>(2,1),false),
new JsonTuple<string,string>("bClose","&Close",new KeyValuePair<int, int>(3,1),false),
new JsonTuple<string,string>("bExit","&Exit",new KeyValuePair<int, int>(4,1),true),
//====================================================
new JsonTuple<string,string>("bCut","&Cut",new KeyValuePair<int, int>(5,0),false),
new JsonTuple<string,string>("bCopy","&Copy",new KeyValuePair<int, int>(6,5),false),
new JsonTuple<string,string>("bPaste","&Paste",new KeyValuePair<int, int>(7,5),false),
new JsonTuple<string,string>("bClear","&Clear",new KeyValuePair<int, int>(8,5),true),
};
return listMenu;
}
private IEnumerable<ButtonItem> GetButtonItem(int pid)
{
var listMenu = GetMenuSetter();
var query = listMenu.Where(x => x.KvType.Value == pid).Select(x =>
{
var bi = new ButtonItem(x.Item1, x.Item2);
bi.Tag = x.KvType; //标记
bi.BeginGroup = x.Tag;
return bi;
});
var plist = query.ToList();
plist
.ForEach(
x => x
.SubItems
.AddRange(
GetButtonItem(((KeyValuePair<int, int>)x.Tag).Key).ToArray()
)
);
return plist;
}
支持多级嵌套,看看效果:
winfrom递归生成菜单,支持多级嵌套