如何更改字形图标' Windows Form C#的DataGridView中的颜色?

时间:2017-11-13 09:48:13

标签: c# winforms sorting datagridview datagridcolumnheader

我默认更改了列标题颜色。现在,我想更改排序字形图标' Windows Form C#的DataGridView中的颜色,当它被排序时:

enter image description here

见上图。该列已排序,但图标的颜色使其可见性不足。

如果可以更改颜色,请告诉我。谢谢!

1 个答案:

答案 0 :(得分:3)

没有用于更改排序图标颜色的属性。作为更改它的选项,您可以处理CellPainting事件并自己绘制单元格。

示例

private void dgv1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    var grid = (DataGridView)sender;
    var sortIconColor = Color.Red;
    if (e.RowIndex == -1 && e.ColumnIndex > -1)
    {
        using (var b = new SolidBrush(BackColor))
        {
            //Draw Background
            e.PaintBackground(e.CellBounds, false);

            //Draw Text Default
            //e.Paint(e.CellBounds, DataGridViewPaintParts.ContentForeground);

            //Draw Text Custom
            TextRenderer.DrawText(e.Graphics, string.Format("{0}", e.FormattedValue),
                e.CellStyle.Font, e.CellBounds, e.CellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Left);

            //Draw Sort Icon
            if (grid.SortedColumn?.Index == e.ColumnIndex)
            {
                var sortIcon = grid.SortOrder == SortOrder.Ascending ? "▲":"▼";

                //Or draw an icon here.
                TextRenderer.DrawText(e.Graphics, sortIcon,
                    e.CellStyle.Font, e.CellBounds, sortIconColor,
                    TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
            }

            //Prevent Default Paint
            e.Handled = true;
        }
    }
}

绘制视觉样式排序图标

要使用“视觉样式”排序图标查看绘图,请查看this post