WPF后台动态生成右键菜单
#region 循环生成右键菜单 private ContextMenu ContextMenus(Dictionary<string, RoutedEventHandler> list) { ContextMenu cm = new ContextMenu(); Style style = (Style)this.FindResource("ContextMenu"); //定义前台显示模板 cm.Style = style; foreach (var dc in list) { MenuItem menu = new MenuItem(); menu.Style = (Style)this.FindResource("JjxyMenuItem"); menu.Header = dc.Key; menu.Click += dc.Value; cm.Items.Add(menu); } return cm; } #endregion
需要右键菜单的地方使用:
Dictionary<string, RoutedEventHandler> dist = new Dictionary<string, RoutedEventHandler>(); //添加右键菜单项,包括名称和事件 dist.Add("添加", add_Click); dist.Add("修改", edit_Click); dist.Add("删除", del_Click); dist.Add("导出", putout_Click); dgrid.ContextMenu = ContextMenus(dist);
添加即可,dgrid为DataGrid实例对象,使用字典,string为菜单名,RoutedEventHandler为菜单事件。