2016-06-08 66 views
2

我的DataGridView上有一個DataGridViewComboBoxColumn。這是我的自定義單元格的繪畫處理程序:自動調整使用自定義繪畫的DataGridViewComboBoxCell

private void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) 
{ 
    if (e.ColumnIndex == 1 && e.RowIndex >= 0) 
    { 
     e.PaintBackground(e.CellBounds, true); 
     //e.PaintContent(e.CellBounds); 

     Graphics g = e.Graphics; 
     Color c = Color.Empty; 
     string s = ""; 
     Brush br = SystemBrushes.WindowText; 
     Brush brBack; 
     Rectangle rDraw; 

     rDraw = e.CellBounds; 
     rDraw = Rectangle.FromLTRB(e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Right, e.CellBounds.Bottom - 1); 

     brBack = Brushes.White; 
     Pen penGridlines = new Pen(dataGridView.GridColor); 
     g.DrawRectangle(penGridlines, rDraw); 
     g.FillRectangle(brBack, rDraw); 
     penGridlines.Dispose(); 

     if (dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null) 
     { 
      ComboboxColourItem oColourItem = (ComboboxColourItem)dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; 
      s = oColourItem.ToString(); 
      c = oColourItem.Value; 
     } 

     int butSize = e.CellBounds.Height; 
     Rectangle rbut = new Rectangle(e.CellBounds.Right - butSize, 
             e.CellBounds.Top, butSize, butSize); 
     ComboBoxRenderer.DrawDropDownButton(e.Graphics, rbut, 
        System.Windows.Forms.VisualStyles.ComboBoxState.Normal); 


     if (c != Color.Empty) 
     { 
      SolidBrush b = new SolidBrush(c); 
      Rectangle r = new Rectangle(e.CellBounds.Left + 6, 
             e.CellBounds.Top + 5, 10, 10); 
      g.FillRectangle(b, r); 
      g.DrawRectangle(Pens.Black, r); 
      g.DrawString(s, Form.DefaultFont, Brushes.Black, 
         e.CellBounds.Left + 25, e.CellBounds.Top + 3); 

      b.Dispose(); 
     } 

     e.Handled = true; 
    } 
} 

當我去了,以自動調整我的填充柱雙擊DVG這個右邊的編輯是發生了什麼:

Autosize

我如何調整行爲,以便在自動調整時考慮組合下拉菜單?

謝謝。

+0

那是油漆之外衆所周知,下拉按鈕的寬度事件? – DonBoitnott

+0

@DonBoitnott不,但寬度在paint事件中指定爲'e.CellBounds.Height',所以也許我們有它? –

+0

我不使用DGV,所以我不知道可能有哪些事件可用,但我會查找(按順序):直接覆蓋列自動大小;調整大小後會發生的事情;或'ColumnWidthChanged'。您應該可以使用其中的一個來確定它是否是您關心的列,併爲按鈕添加更多寬度。 AutoSize永遠不會知道它,所以你必須手工完成。 – DonBoitnott

回答

2

當您雙擊列標題分隔符以使列自動調整大小時,它將使列寬等於最寬的單元格。在自動調整大小模式的組合框單元的寬度是使用計算:

  • 格式化值的寬度
  • 組合框按鈕
  • 細胞風格填充
  • 錯誤圖標寬度
  • 一些額外的填充的寬度周圍的文本和按鈕和圖標

快速修復

在你的情況下,當計算單元格的自動大小時,那些彩色矩形將佔用空間,但它們的寬度和空間不會被計算。

作爲一個簡單的解決方案,您可以在列中添加一些填充。您可以在設計人員中編輯列,並在列中設置DefaultCellStyle的填充。還使用代碼,你可以,例如寫:

column.DefaultCellStyle.Padding = new Padding(16,0,16,0); 

長期的解決方案

如果列是可重複使用的列類型,我建議你創建自定義字段類型。然後,您可以封裝繪畫邏輯並計算您的自定義單元格中的大小和其他一些功能。如果你決定創建自定義單元格,你會發現相關問題有用的這些方法:

+0

謝謝!很棒。 –

+0

不客氣:) –

+1

把'ComboBoxRenderer.DrawDropDownButton ...'在繪製結束時,按鈕應該呈現在文本上方。目前正如你所見,文本是通過組合框按鈕繪製的。繪製文本後,應繪製組合框按鈕。 –