4

我使用ContainerControl作为基础创建了一个简单的自定义面板。我添加了自定义属性来创建边框和渐变背景。如果我覆盖 OnPaint 和 OnPaintBackground,则父级的所有子控件都会继承渐变和边框样式。作为一种解决方法,我使用了父母 BackgroundImage 属性,它工作正常,但有一些随机的怪癖。必须有更好的方法来解决这个问题,但我没有找到解决方案。是否有任何通过 Interop 或其他 C# 方法来解决此问题的 Window API 函数?如果是这样,请提供一个例子。

编辑!这是被复制的样式(丑陋的例子,但很重要):

在此处输入图像描述

编辑 2!这是一个简单的硬编码 ContainerControl,没有所有属性、设计器属性等。

public class Container : ContainerControl
{
    protected override void OnPaintBackground( PaintEventArgs e )
    {
        using ( var brush = new LinearGradientBrush( e.ClipRectangle, Color.Red, Color.Blue, LinearGradientMode.Vertical ) )
        {
            e.Graphics.FillRectangle( brush, e.ClipRectangle );
        }
    }
}
4

3 回答 3

3

如果Label创建控件时将其BackColor属性设置为Color.Transparent,它将最终调用其父级的OnPaintBackground()实现。

如果您像这样修改 Jon 的示例:

var label = new Label { 
    Text = "Label",
    Location = new Point(20, 50),
    BackColor = Color.Transparent
};

然后您将重现该问题。

但是,有一个简单的解决方法。问题来自您创建线性渐变画笔的方式。由于您传递e.ClipRectangle给它的构造函数,渐变的形状将根据正在呈现的控件(容器或标签)而有所不同。另一方面,如果您传递容器的ClientRectangle,那么渐变将始终具有相同的形状,结果应该是您正在寻找的结果:

protected override void OnPaintBackground(PaintEventArgs e)
{
    using (var brush = new LinearGradientBrush(ClientRectangle,
           Color.Red, Color.Blue, LinearGradientMode.Vertical)) {
        e.Graphics.FillRectangle(brush, e.ClipRectangle);
    }
}

结果是:

在此处输入图像描述

于 2012-08-23T07:40:46.040 回答
0

初始化控件创建/加载的属性

然后“INVALIDATE”控件强制重绘控件

于 2012-08-21T18:53:42.577 回答
0

我不能简单地在我的 Windows 7 机器上重现这个 - 这表明它可能是您在设计器中设置的属性之一。简短而完整的程序:

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

public class GradientContainer : ContainerControl
{
    protected override void OnPaintBackground(PaintEventArgs e)
    {
        using (var brush = new LinearGradientBrush(e.ClipRectangle, 
                       Color.Red, Color.Blue, LinearGradientMode.Vertical))
        {
            e.Graphics.FillRectangle(brush, e.ClipRectangle);
        }
    }
}

class Test
{
    static void Main()
    {
        var label = new Label { 
            Text = "Label",
            Location = new Point(20, 50)
        };
        var container = new GradientContainer {
            Size = new Size(200, 200),
            Location = new Point(0, 0),
            Controls = { label }
        };        

        Form form = new Form {
            Controls = { container },
            Size = new Size(300, 300)
        };
        Application.Run(form);
    } 
}

结果:

标签没有渐变

于 2012-08-22T06:01:09.487 回答