[英]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.