2012-06-15 83 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