1

我正在为正在开发的控件继承 DataGridView 控件。我的目标是让每一行的颜色代表一个可以在运行时改变的对象状态。我的对象实现了 Observable 设计模式。所以我决定开发自己的 DataGridViewRow 类,实现观察者模式并让我的行观察对象。在这个类中,我有这个方法:

public void UpdateColors(int state)
{
    DefaultCellStyle.BackColor = m_ETBackColors[state];
    DefaultCellStyle.ForeColor = m_ETForeColors[state];
}

我暂时无法观察我的对象,因此,为了测试颜色变化,我在 SelectionChanged 事件中对选定的行调用我的 UpdateColors 方法。

现在是它不起作用的时刻!我之前选择的行保持蓝色(就像它们被选中时一样),当我滚动时,单元格文本是分层的。我尝试调用 DataGridView.Refresh(),但这也不起作用。

我必须添加我的 datagridview 没有绑定到数据源:我不知道在运行之前我有多少列,所以我手动提供它。

谁能告诉我我做错了什么?

========== 更新 ==========

这有效:

public void UpdateColors(int state)
{
    DefaultCellStyle.BackColor = System.Drawing.Color.Yellow;
    DefaultCellStyle.ForeColor = System.Drawing.Color.Black;
}

但这不起作用:

public void UpdateColors(int state)
{
    DefaultCellStyle.BackColor = m_ETBackColors[nEtattech];
    DefaultCellStyle.ForeColor = m_ETForeColors[nEtattech];
}

和 :

    System.Drawing.Color[] m_ETBackColors = new System.Drawing.Color[] { };
    System.Drawing.Color[] m_ETForeColors = new System.Drawing.Color[] { };

没有数组溢出:它们是构造函数参数。

4

2 回答 2

1

好的,发现错误了。我使用的颜色是这样创建的:

System.Drawing.Color.FromArgb(value)

不好的是 value 是一个整数,表示 alpha 设置为 0 的颜色。
感谢这篇文章:MSDN social post,我了解到单元格样式不支持 ARGB 颜色,除非 alpha 设置为 255(它们只支持 RGB颜色)。

所以我结束了使用这个,它有效,但肯定有一个更优雅的方式:

System.Drawing.Color.FromArgb(255, System.Drawing.Color.FromArgb(value));
于 2012-06-18T15:29:38.157 回答
0

使用CellFormatting事件来做到这一点:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
  if (this.dataGridView1.Rows[e.RowIndex].Cells["SomeStuff"].Value.ToString()=="YourCondition")
    this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
  else
    this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
}
于 2012-06-15T15:04:18.300 回答