如果您在单元格中除了有问题的角色之外还有其他任何内容(您需要进行某种形式的自定义绘画),则没有简单的方法可以做到这一点。
如果您只有这些字符,那么使用 CellFormatting 事件很容易:
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
e.CellStyle.Font = new Font("Arial Unicode MS", 12);
if (dataGridView1.Columns[e.ColumnIndex].Name == "CorrectColumnName")
{
if (e.Value == "▲")
e.CellStyle.ForeColor = Color.Green;
else if (e.Value == "▼")
e.CellStyle.ForeColor = Color.Red;
else
e.CellStyle.ForeColor = Color.Black;
}
}
如果您确实想要在同一个单元格中使用不同的颜色,则需要类似以下代码(这将处理 CellPainting 事件):
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == -1 || e.RowIndex == -1)
return;
if (dataGridView1.Columns[e.ColumnIndex].Name == "CorrectColumnName")
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All & ~DataGridViewPaintParts.ContentForeground);
if (e.FormattedValue.ToString().StartsWith("▲", StringComparison.InvariantCulture))
{
RenderCellText(Color.Green, e);
}
else if (e.FormattedValue == "▼")
{
RenderCellText(Color.Red, e);
}
else
RenderCellText(SystemColors.WindowText, e);
e.Handled = true;
}
}
private void RenderCellText(Color color, DataGridViewCellPaintingEventArgs e)
{
string text = e.FormattedValue.ToString();
string beginning = text.Substring(0, 1);
string end = text.Substring(1);
Point topLeft = new Point(e.CellBounds.X, e.CellBounds.Y + (e.CellBounds.Height / 4));
TextRenderer.DrawText(e.Graphics, beginning, this.dataGridView1.Font, topLeft, color);
Size s = TextRenderer.MeasureText(beginning, this.dataGridView1.Font);
Point p = new Point(topLeft.X + s.Width, topLeft.Y);
TextRenderer.DrawText(e.Graphics, end, this.dataGridView1.Font, p, SystemColors.WindowText);
}