2016-04-25 68 views
1

我有一個自定義的DataGridView,它具有從DataGridViewTextBoxCell和DataGridViewCheckBoxCell繼承的許多不同的單元類型。DataGridViewTextBoxCell中的主機複選框

這些自定義單元格中的每一個都有一個屬性,用於設置稱爲CellColour的背景顏色(網格的某些功能需要)。

爲了簡單起見,我們將採取兩種自定義單元格:

public class FormGridTextBoxCell : DataGridViewTextBoxCell 
{ 
    public Color CellColour { get; set; } 
    ... 
} 

public class FormGridCheckBoxCell : DataGridViewCheckBoxCell 
{ 
    public Color CellColour { get; set; } 
    ... 
} 

問題:

這意味着,每一次我要爲一個網格行的CellColour屬性,它同時包含列鍵入FormGridTextBoxColumn和FormGridCheckBoxColumn(它們分別具有上述的自定義類型的細胞CellTemplaes)我必須做到以下幾點:

if(CellToChange is FormGridTextBoxCell) 
{ 
    ((FormGridTextBoxCell)CellToChange).CellColour = Color.Red; 
} 
else if (CellToChange is FormGridCheckBoxCell) 
{ 
    ((FormGridCheckBoxCell)CellToChange).CellColour = Color.Red; 
} 

當您有3種以上不同的細胞類型時,這會變得很艱難,我相信有這樣做的更好方法。

解決方案徵詢:

我已經在我的頭上,如果我可以創建一個從DataGridViewTextBoxCell繼承一個類,然後讓自定義單元格類型依次從該類繼承:

public class FormGridCell : DataGridViewTextBoxCell 
{ 
    public Color CellColour { get; set } 
} 

public class FormGridTextBoxCell : FormGridCell 
{ 
    ... 
} 

public class FormGridCheckBoxCell : FormGridCell 
{ 
    ... 
} 

然後,我將只需要做到以下幾點:

if(CellToChange is FormGridCell) 
{ 
    ((FormGridCell)CellToChange).CellColour = Color.Red; 
    ... 
} 

不管有多少自定義的細胞類型有(因爲他們將全部來自FormGridCell繼承);任何特定的控制驅動單元格類型都將在其中實現Windows窗體控件。

爲什麼這是一個問題:

我已經嘗試了本文以下內容:

Host Controls in Windows Forms DataGridView Cells

該方法適用於自定義DateTime拾取但是託管在DataGridViewTextBoxCell一個複選框魚的不同水壺因爲有不同的屬性來控制單元格的值。

如果有一種更簡單的方法來使用DataGridViewTextBoxCell開始,並將繼承類中的數據類型更改爲預定義的數據類型,那麼我可以接受建議,但是核心問題是在DataGridViewTextBoxCell。

回答

1

正如我相信你發現,一個類可能只能從一個基類繼承。你所想是interface,如:

public interface FormGridCell 
{ 
    Color CellColor { get; set; } 
} 

從那裏,你可以很類似創建的子類,從各自DataGridViewCell類型繼承以及實施interface

public class FormGridTextBoxCell : DataGridViewTextBoxCell, FormGridCell 
{ 
    public Color CellColor { get; set; } 
} 

public class FormGridCheckBoxCell : DataGridViewCheckBoxCell, FormGridCell 
{ 
    public Color CellColor { get; set; } 
} 

在這一點上,使用如你所願,通過CellTemplate創建細胞,並根據需要只投細胞的interface類型,你可以自由地做你希望(看到的結果可視化,我設置單元格的背景色爲例):

if (cell is FormGridCell) 
{ 
    (cell as FormGridCell).CellColor = Color.Green; 
    cell.Style.BackColor = Color.Green; 
} 
else 
{ 
    cell.Style.BackColor = Color.Red; 
} 
+0

這正是我之後的事情。非常感謝!是的,問題的根源主要是因爲只能從單個基類繼承。 –

相關問題