c# DevExpress GridView实现鼠标移动到单元格文字内容上后变手形,并触发RowCellClick事件

我们都知道,在.net自带的Winform控件DataGridView控件有一个 CellContentClick 事件,该事件是在点击单元格内容的时候触发,很好用

那么在DevExpress中的GridView中是否有类似事件呢,很遗憾,DEV中只提供了一个RowCellClick事件,这个事件有个弊端就是点击单元格

空白的地方也会触发事件,跟我的要求不一样,我希望的是鼠标移动单元格文字上鼠标变手型,并能点击,鼠标移动到单元格空白处鼠标恢复

默认且点击也无效,以下代码利用MouseMove配合RowCellClick事件可以很好的解决我的问题,具体代码如下

private void bgvCharge_MouseMove(object sender, MouseEventArgs e)
        {
            BandedGridHitInfo info = this.bgvCharge.CalcHitInfo(e.X, e.Y);
            if (info.InRowCell)
            {              
                //先获取单元格文字内容的宽度和高度的
                string _value = this.bgvCharge.GetRowCellValue(info.RowHandle, info.Column).ToString();
                Graphics g = this.CreateGraphics();
                SizeF size = g.MeasureString(_value, info.Column.AppearanceCell.Font);
                //获取单元格所在的坐标信息
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridViewInfo info2 = this.bgvCharge.GetViewInfo() as DevExpress.XtraGrid.Views.Grid.ViewInfo.GridViewInfo;
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridCellInfo cellInfo = info2.GetGridCellInfo(info.RowHandle, info.Column);
                //新建一个矩形区域用来存放单元格文字占用的矩形区域
                Rectangle rectangle = new Rectangle();
                rectangle.X = cellInfo.Bounds.X + cellInfo.Bounds.Width / 2 - (int)(size.Width / 2) - 1;
                rectangle.Y = cellInfo.Bounds.Y + cellInfo.Bounds.Height / 2 - (int)(size.Height / 2) + 1;
                rectangle.Width = (int)size.Width;
                rectangle.Height = (int)size.Height;
                //如果鼠标位置在该矩形区域内,鼠标变手形
                if (rectangle.Contains(e.Location))
                {
                    this.gridCharge.Cursor = Cursors.Hand;
                }
                else
                {
                    this.gridCharge.Cursor = Cursors.Default;
                }               
            }
            else
            {
                this.gridCharge.Cursor = Cursors.Default;
            }
        }

        private void bgvCharge_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            //如果鼠标不是手形状态,则点击事件退出无效
            if (this.gridCharge.Cursor != Cursors.Hand) return;
            MessageBox.Show("Test");
        }

 

posted @ 2023-03-02 16:48  huang1314wei  阅读(736)  评论(0)    收藏  举报