将datagrid视图背景设置为透明

我试图将数据网格视图的背景颜色设置为从属性“透明”,但它表示“不是有效的属性”。

我该怎么做?

我做了一个特定问题的解决方案(当网格包含在带有背景图像的表格中)时,通过简单修改你可以调整它来创建一个通用的透明网格,只要询问父母是否有背景图像,否则只需使用父背景颜色绘制你的网格,就是这样。

您必须从DataGridViewinheritance并覆盖PaintBackground方法,如下所示:

protected override void PaintBackground(Graphics graphics, Rectangle clipBounds, Rectangle gridBounds) { base.PaintBackground(graphics, clipBounds, gridBounds); Rectangle rectSource = new Rectangle(this.Location.X, this.Location.Y, this.Width, this.Height); Rectangle rectDest = new Rectangle(0, 0, rectSource.Width, rectSource.Height); Bitmap b = new Bitmap(Parent.ClientRectangle.Width, Parent.ClientRectangle.Height); Graphics.FromImage(b).DrawImage(this.Parent.BackgroundImage, Parent.ClientRectangle); graphics.DrawImage(b, rectDest, rectSource, GraphicsUnit.Pixel); SetCellsTransparent(); } public void SetCellsTransparent() { this.EnableHeadersVisualStyles = false; this.ColumnHeadersDefaultCellStyle.BackColor = Color.Transparent; this.RowHeadersDefaultCellStyle.BackColor = Color.Transparent; foreach (DataGridViewColumn col in this.Columns) { col.DefaultCellStyle.BackColor = Color.Transparent; col.DefaultCellStyle.SelectionBackColor = Color.Transparent; } } 

我用Deumber的解决方案做到了这一点并且它可以工作,但是通过添加一些小的改进我会避免一些麻烦:

A.滚动DGV会使背景变得混乱。 解决方案:把它放在某个地方:

 public partial class main : Form { protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ExStyle |= 0x02000000; return cp; } } } 

背景仍然会滚动,但在每个滚动步骤后立即纠正。 它很明显,但对我来说是可以接受的。 有没有人知道更好的解决方案来支持滚动这个?

B.设计师使用它有麻烦。 解:

 protected override void PaintBackground(Graphics graphics, Rectangle clipBounds, Rectangle gridBounds) { base.PaintBackground(graphics, clipBounds, gridBounds); if (main.ActiveForm != null && this.Parent.BackgroundImage != null) { Rectangle rectSource = new Rectangle(this.Location.X, this.Location.Y, this.Width, this.Height); Rectangle rectDest = new Rectangle(-3, 3, rectSource.Width, rectSource.Height); Bitmap b = new Bitmap(Parent.ClientRectangle.Width, Parent.ClientRectangle.Height); Graphics.FromImage(b).DrawImage(this.Parent.BackgroundImage, Parent.ClientRectangle); graphics.DrawImage(b, rectDest, rectSource, GraphicsUnit.Pixel); SetCellsTransparent(); } } 

现在,设计师就像DGV一样对待它。 如果您想要在没有ActiveForm的情况下绘制DGV,它将失败,但通常情况并非如此。 当你可能仍然想要使用设计器时,也可以保留if-line,并在发布时删除它。

无法在DataGridView BackGroundColor属性中使用透明颜色。

所以我决定将这个属性与父级的BackColor同步。 WinForms良好的旧数据绑定function非常擅长:

 myDataGridView.DataBindings.Add(nameof(DataGrid.BackgroundColor), this, nameof(Control.BackColor)); 

就在InitializeComponents();

我知道这很老了,但是效果很好。

将datagridview的backcolor设置为与表单颜色相同。 为此,请选择datagridview:转到Properties – > RowTemplate – > DefaultCellStyle – > BackColor并选择表单的颜色。

您需要将所有行和列设置为透明。 更简单的方法是:

 for (int y = 0; y < gridName.Rows[x].Cells.Count; y++) { yourGridName.Rows[x].Cells[y].Style.BackColor = System.Drawing.Color.Transparent; }