DevExpress GridView 鼠标悬停颜色追踪(行或单元格)
2019年07月12日 15:17:02 涛神-Dev 阅读数 41 标签: GridView行追踪单元格追踪 更多
个人分类: DevExpressWinformGridControl
如何将GridView做成类似网页的列表那样,鼠标移动的是行背景颜色跟着变,也就是所为的鼠标悬停追踪,
效果如下:
代码如下:
-
public class ViewStyleHelper
-
{
-
bool enable;
-
public bool Enable
-
{
-
get { return enable; }
-
set
-
{
-
enable = value;
-
UnRegisterEvent();
-
if (enable)
-
{
-
RegisterEvent();
-
}
-
else
-
{
-
View.RefreshData();
-
}
-
}
-
}
-
bool byRow;
-
/// <summary>
-
/// 真为行,假为单元格
-
/// </summary>
-
public bool ByRow
-
{
-
get { return byRow; }
-
set
-
{
-
byRow = value;
-
UnRegisterEvent();
-
if(enable)
-
RegisterEvent();
-
}
-
}
-
public DevExpress.XtraGrid.Views.Grid.GridView View { get; private set; }
-
/// <summary>
-
/// 当前列
-
/// </summary>
-
GridColumn currentCol;
-
/// <summary>
-
/// 当前行
-
/// </summary>
-
int currentRowHandle;
-
public ViewStyleHelper(DevExpress.XtraGrid.Views.Grid.GridView view,bool byRow=true)
-
{
-
View = view;
-
this.byRow = byRow;
-
Enable = true;
-
view.MouseLeave += (s, e) =>
-
{
-
currentCol = null;
-
currentRowHandle = int.MinValue;
-
view.RefreshData();
-
};
-
}
-
void RegisterEvent()
-
{
-
View.MouseMove += onm ouseMove;
-
if (!byRow)
-
View.RowCellStyle += OnRowCellStyle;
-
else
-
{
-
View.RowStyle += OnRowStyle;
-
}
-
}
-
void UnRegisterEvent()
-
{
-
View.MouseMove -= onm ouseMove;
-
View.RowCellStyle -= OnRowCellStyle;
-
View.RowStyle -= OnRowStyle;
-
}
-
private void onm ouseMove(object sender, MouseEventArgs e)
-
{
-
var view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
-
var info = view.CalcHitInfo(e.Location);
-
bool refresh = false;
-
if (currentCol != info.Column || currentRowHandle != info.RowHandle)
-
{
-
refresh = true;
-
}
-
if (info.InDataRow)
-
{
-
currentCol = info.Column;
-
currentRowHandle = info.RowHandle;
-
}
-
else
-
{
-
currentCol = null;
-
currentRowHandle = int.MinValue;
-
}
-
if (refresh)
-
view.RefreshData();
-
}
-
private void OnRowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
-
{
-
if (e.RowHandle == currentRowHandle)
-
{
-
e.Appearance.BackColor = Color.FromArgb(108, 178, 235);
-
e.HighPriority = true;
-
}
-
}
-
private void OnRowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
-
{
-
if (e.Column == currentCol && e.RowHandle == currentRowHandle)
-
{
-
e.Appearance.BackColor = Color.FromArgb(108, 178, 235);
-
}
-
}
-
}
调用代码:
-
ViewStyleHelper helper;
-
private void Form1_Load(object sender, EventArgs e)
-
{
-
helper = new ViewStyleHelper(gridView1);
-
var dt = CreateDt();
-
gridControl1.DataSource = dt;
-
}