2012-06-15 84 views
1

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

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[] { }; 

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

回答

1

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

System.Drawing.Color.FromArgb(value) 

坏事是该值表示Alpha设置颜色为0
由于这个职位的整数:MSDN social post,我了解到,单元格样式唐不支持ARGB颜色,除非alpha设置为255(它们只支持RGB颜色)。

所以我最终用这个,它的工作原理,但肯定是一个更优雅的方式:

System.Drawing.Color.FromArgb(255, System.Drawing.Color.FromArgb(value)); 
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; 
} 
+0

我已经尝试过这一点,我在UpdateColors行设置自定义颜色属性,在我的DataGrid使用CellFormatting事件的,但它没有工作: '私人无效DataGridViewEtat_Technique_CellFormatting(对象发件人,System.Windows.Forms.DataGridViewCellFormattingEventArgs E) { DataGridViewTechnicalStateRow行=行[e.RowIndex如DataGridViewTechnicalStateRow; row.DefaultCellStyle.BackColor = row.BCL; row.DefaultCellStyle.ForeColor = row.FCL; }' – Rifu