2016-04-25 67 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

这正是我之后的事情。非常感谢!是的,问题的根源主要是因为只能从单个基类继承。 –

相关问题