2016-04-11 21 views
2

私はDataGridViewを持っており、これらの値に異なるForeColorを与えることによって変更される演算子を表示します。オペレーターは、[破棄]ボタンをクリックすると、すべての変更を破棄することができます。その場合、私はセルに継承されたスタイルを使用させる必要があります。DataGridViewCellStyleを継承した値に復元する方法

私の問題は、いったん変更したことを示すCellStyleを作成したら、これを元に戻すことができないため、セルが継承されたスタイルを使用することです。

私はいくつかの研究を行いました。記事Cell Styles in the Windows Forms DataGridView ControlでMSDNは警告している:

は、セルのスタイルプロパティに格納された値をキャッシュ かかわらず、特定のスタイル値が設定されているかどうかの重要です。 スタイル設定を一時的に置き換える場合は、元の " "の状態に復元すると、セルがより高いレベルのスタイル の設定を継承することに戻ります。

ああ、これは動作していないよう:

DataGridViewCell cell = ...; 

Debug.Assert(!cell.HasStyle);   // cell is not using its own style 
var cachedColor = cell.Style.ForeColor; // cache the original color 
cell.Style.ForeColor = Color.Red;  // indicate a change 
Debug.Assert(cell.HasStyle);   // now cell is using its own style 

// restore to the 'not set' state: 
cell.Style.ForeColor = cachedColor; 
Debug.Assert(!cell.HasStyle);   // exception, not using inherited style 
cell.Style = cell.InheritedStyle;  // try other method to restore 
Debug.Assert(!cell.HasStyle);   // still exception 

そこで質問:状態「を設定していない」が元にスタイル設定を復元する方法は?

答えて

1

私はCell.StyleとCell.InheritedStyleについて完全に誤解しているようです。

私は、継承されたスタイルが行/交互行/ DataGridViewから継承されたスタイルであり、スタイルが結果のスタイルであると考えました。

NOT!

結果のスタイルは、DataGridViewCell.InheritedStyleです。このスタイルはDataGridViewCell.Styleに等しいか、またはこれがnull値を持つ場合、DataGridViewRow.InheritedStyleのスタイルに等しくなります。これはDataGridViewRow.DefaultStyleの値と等しくなります。またはこれがnullの場合、DataGridView.AlternatingRowsDefaultCellStyleなど

実際にどのスタイルが使用されているかを知るには、DataGridViewCell.InheritedStyleを取得して特定のスタイルを指定すると、DataGridViewCell.Styleのプロパティが自動的に作成され、取得時に継承された値で埋められます。

DataGridViewCell.Styleを破棄するには、nullに設定するだけです。その後、DataGridViewCell.HasStyleはfalseになり、DataGridViewCell.InheritedStyleは、Alternating Rows/All Rowsから継承されたスタイルになります。

例: - ボタン「変更」はAliceBlue に赤に現在のセルの前景色と完全な行のBackColorプロパティを変更します - ボタンを「破棄」は

既定のセルスタイルに復元されます
private void buttonChange_Click(object sender, EventArgs e) 
{ 
    DataGridViewCell cell = this.dataGridView1.CurrentCell; 
    DataGridViewRow row = cell.OwningRow; 

    if (!row.HasDefaultCellStyle) 
    { 
     row.DefaultCellStyle.BackColor = Color.AliceBlue; 
    } 

    if (!cell.HasStyle) 
    { 
     cell.Style.ForeColor = Color.Red; 
    } 
} 

結果:現在のセルが赤フォアグラウンド色で示され、現在の行がAliceBlueの背景色で示されている

private void buttonDiscard_Click(object sender, EventArgs e) 
{ 
    DataGridViewCell cell = this.dataGridView1.CurrentCell; 
    DataGridViewRow row = cell.OwningRow; 

    if (row.HasDefaultCellStyle) 
    { 
     row.DefaultCellStyle = null; 
     Debug.Assert(!row.HasDefaultCellStyle); 
    } 
    if (cell.HasStyle) 
    { 
     cell.Style = null; 
     Debug.WriteLine(!cell.HasStyle); 
    } 
} 

結果:現在のセル及び現在の行は、それらの起源で示されていますアルカラー

関連する問題