[英]Remove sorting arrow in datagridview header and put the text in the center of the box
我正在开发一个项目,它需要标题文本位于中心,当点击标题时,它将进行排序。 但问题是,有一个排序箭头图标,即使它没有显示它将文本推向左侧。 我想要实现的是
- 删除排序箭头并将文本放在中心但仍保留排序功能
p / s:我尝试处理单元格事件绘制并重新绘制headercell中的所有内容,除了.contentbackground箭头消失但文本仍然向左推。 这是代码:
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex == -1)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All &~DataGridViewPaintParts.ContentBackground);
e.Handled = true;
}
}
- 保持排序箭头,但始终显示它
我正在使用vb .net但是c#中的代码很好
标题现在如何
我多么希望标题看起来像
非常感谢你
要在中间对齐列标题文本,可以依赖DataGridView
属性。 但是对于自定义排序图标,您需要自定义绘制。
要设置列标题文本对齐方式:
Alignment
的财产ColumnHeadersDefaultCellStyle
到MiddleCenter
。 要绘制自定义排序图标:
处理CellPainting
事件并检查我们是否正在绘制标题:
if (e.RowIndex == -1) //It's header cell
画细胞背景
e.PaintBackground(e.CellBounds, false);
绘制内容前景(文本):
e.Paint(e.CellBounds, DataGridViewPaintParts.ContentForeground);
使用DrawImage
或绘制合适的字符来绘制自定义排序字形:
if (grid.SortedColumn?.Index == e.ColumnIndex) { var sortIcon = grid.SortOrder == SortOrder.Ascending ? "▲":"▼"; //Just for example I rendered a character, you can draw an image. TextRenderer.DrawText(e.Graphics, sortIcon, e.CellStyle.Font, e.CellBounds, sortIconColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right); }
停止默认绘画
e.Handled = true;
注 - 绘制视觉样式排序图标
如果要绘制默认排序图标:
e.Paint(e.CellBounds, DataGridViewPaintParts.ContentBackground);
仅作为示例,绘制视觉样式排序图标:
if (grid.SortedColumn?.Index == e.ColumnIndex) { var sortIcon = grid.SortOrder == SortOrder.Ascending ? VisualStyleElement.Header.SortArrow.SortedUp : VisualStyleElement.Header.SortArrow.SortedDown; var renderer = new VisualStyleRenderer(sortIcon); var size = renderer.GetPartSize(e.Graphics, ThemeSizeType.Draw); renderer.DrawBackground(e.Graphics, new Rectangle(e.CellBounds.Right - size.Width, e.CellBounds.Top, size.Width, e.CellBounds.Height)); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.