在datagridview 实现右键工具菜单ContextMenuStrip,处理列显示等功能

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Common.Components
{
    public partial class DataGridViewContextMenuStrip : ContextMenuStrip
    {

        private void View_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            this.ShowMenu(sender, e);
        }

        public event Action<SizeGroup, Control> SizeGroupChanged;
        public DataGridViewContextMenuStrip()
        {
            InitializeComponent();
            List<ToolStripItem> stripItems = new List<ToolStripItem>();
            foreach (var item in CommonGlobalCache.SizeGroupList)
            {
                if (item.Enabled)
                {
                    stripItems.Add(new ToolStripMenuItem(item.DisplayName, null, toolStripMenuItem1_Click) { Tag = item });
                }
            }
            toolStripMenuItem1.DropDownItems.AddRange(stripItems.ToArray());
        }

        public void ShowMenu(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 && e.ColumnIndex == -1)
            {
                view = sender as DataGridView;
                this.Show(view, new Point(1, 1));
            }
        }

        private DataGridView view;
        public DataGridView DataGridView
        {
            get { return view; }
            set
            {
                if (value != null)
                {
                    view = value;
                    view.CellClick -= View_CellClick;
                    view.CellClick += View_CellClick;
                    CommonGlobalUtil.ChangeSizeGroup(view, CommonGlobalCache.DefaultSizeGroup);
                } 
            }
        }

        private SizeGroup sizeGroup;
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
            if (menuItem != null && menuItem.Tag != null)
            {
                if (menuItem.Tag is SizeGroup)
                {
                    sizeGroup = menuItem.Tag as SizeGroup; 
                    CommonGlobalUtil.ChangeSizeGroup(view, sizeGroup);
                    SizeGroupChanged?.Invoke(sizeGroup, view);
                    return;
                }
            }
        }
    }
}
 

猜你喜欢

转载自blog.csdn.net/jasonhongcn/article/details/86486852