孩子继承了父母的外表

时间:2012-08-17 12:35:56

标签: c# winforms custom-controls containers onpaint

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

编辑!以下是正在复制的样式(丑陋的例子,但重点突出):

enter image description here

编辑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 );
        }
    }
}

3 个答案:

答案 0 :(得分:2)

如果创建的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);
    }
}

结果是:

enter image description here

答案 1 :(得分:0)

初始化控件create / load

上的属性

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

答案 2 :(得分: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);
    } 
}

结果:

Label has no gradient

相关问题