How to change 'sort glyph icon' color in D

2019-08-11 22:06发布

I've changed the column header color by default. Now, I want to change the 'sort glyph icon' color in DataGridView of Windows Form C# when it gets sorted:

enter image description here

See the above picture. The column is sorted but icon's color makes it's visibility inadequate.

Please let me know if it's color can be changed. Thanks!

1条回答
三岁会撩人
2楼-- · 2019-08-11 22:58

There is no property for changing color of sort icon. As an option to change it, you can handle CellPainting event and draw the cell yourself.

Example

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;
        }
    }
}

Draw Visual Styles Sort Icon

To see drawing with Visual Styles sort icon, take a look at this post.

查看更多
登录 后发表回答