我有一个自定义的DataGridView,它有许多不同的单元格类型,它们是从DataGridViewTextBoxCell和DataGridViewCheckBoxCell继承的。
每个自定义单元格都有一个属性,用于设置名为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;
}当你有不同的细胞类型,这变得非常困难,我相信有一个更好的方法来做到这一点。
寻求解决办法:
我想,如果我能够创建一个继承自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控件。
为什么这是个问题:
我试着遵循这篇文章:
Windows窗体DataGridView单元格中的宿主控件
但是,对于自定义DateTime选择器来说,在DataGridViewTextBoxCell中承载一个CheckBox是一个不同的鱼缸,因为有不同的属性来控制单元格的值。
如果有一种更简单的方法可以从DataGridViewTextBoxCell开始并将继承类中的数据类型更改为预定义的数据类型,那么我可以接受一些建议,但是,核心问题是在DataGridViewTextBoxCell中托管一个复选框。
发布于 2016-04-26 00:20:49
我相信您已经发现,单个类只能继承一个基类。您需要的是一个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类型,您可以随意使用(为了直观地看到结果,我以单元格的BackColor为例):
if (cell is FormGridCell)
{
(cell as FormGridCell).CellColor = Color.Green;
cell.Style.BackColor = Color.Green;
}
else
{
cell.Style.BackColor = Color.Red;
}https://stackoverflow.com/questions/36851838
复制相似问题