c# - 将数据 GridView 背景设置为透明

标签 c# winforms datagridview transparency background-color

我试图将数据 GridView 的背景颜色设置为对属性“透明”,但它显示“不是有效属性”。

我该怎么做?

最佳答案

我通过简单的修改针对特定问题(当网格包含在带有背景图像的表单中时)做了这个解决方案,您可以调整它以创建通用透明网格,只需询问父级是否有背景图像,否则只需使用用于绘制网格的父背景色,仅此而已。

您必须像这样继承自 DataGridView 并覆盖 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;
    }
}

关于c# - 将数据 GridView 背景设置为透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1330220/

相关文章:

c# - 如何使用 C# 将 Excel 工作表中特定行或单元格的字体加粗?

c# - 统一: Texturing a Shoreline in a Hexgrid

c# - 停靠栏更改时 UserControl 未在 FlowLayoutPanel 中呈现

c++ - Visual Studio 应用程序依赖

c# - 在当前打开的应用程序顶部显示隐藏的窗口窗体

c# - AllowUserToAddRows 不适用于 DataGridView 上的 List<> 数据源

c# - 如何在 C# 中播放特定的 Windows 错误声音

c# - connection.open 挂起/卡住。我的连接字符串有什么问题?

c# - 更新输入类型=文本值或文本框控件调整大小事件

c# - 如何按日期对 DataGridView 列(绑定(bind)到 BindingSource)进行排序?