1

我有一个自定义 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 中托管一个复选框。

4

1 回答 1

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类型,您可以随意做任何事情(为了直观地查看结果,我将单元格的 BackColor 设置为示例):

if (cell is FormGridCell)
{
    (cell as FormGridCell).CellColor = Color.Green;
    cell.Style.BackColor = Color.Green;
}
else
{
    cell.Style.BackColor = Color.Red;
}
于 2016-04-26T00:20:49.217 回答