我有一个自定义 DataGridView,其中包含许多从 DataGridViewTextBoxCell 和 DataGridViewCheckBoxCell 继承的不同单元格类型。
这些自定义单元格中的每一个都有一个用于设置背景颜色(网格的某些功能需要)的属性,称为 CellColour。
为简单起见,我们将采用两个自定义单元格:
public class FormGridTextBoxCell : DataGridViewTextBoxCell
{
public Color CellColour { get; set; }
...
}
public class FormGridCheckBoxCell : DataGridViewCheckBoxCell
{
public Color CellColour { get; set; }
...
}
问题:
这意味着每次我想为包含 FormGridTextBoxColumn 和 FormGridCheckBoxColumn 类型的列(分别具有上述自定义单元格类型的 CellTemplaes)的 Grid Row 设置 CellColour 属性时,我必须执行以下操作:
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 窗体控件。
为什么这是一个问题:
我试过关注这篇文章:
Windows 窗体 DataGridView 单元格中的宿主控件
这适用于自定义 DateTime 选择器,但是在 DataGridViewTextBoxCell 中托管 CheckBox 是另一回事,因为有不同的属性来控制单元格的值。
如果有一种更简单的方法从 DataGridViewTextBoxCell 开始并将继承类中的数据类型更改为预定义的数据类型比这更容易,那么我愿意接受建议,但核心问题是在 DataGridViewTextBoxCell 中托管一个复选框。