c# - 我想让面板有一个粗边框。我能以某种方式设置它吗?

标签 c# winforms visual-studio-2008 controls

我想让一个面板有一个粗边框。我能以某种方式设置它吗?

PS,我正在使用 C#。对比 2008。

最佳答案

吉姆,

我制作了一个用户控件并给出了一个 ParentControlDesigner。正如我在评论中指出的那样,这不是您所要求的完美解决方案。但这应该是一个很好的起点。哦,仅供引用,我也有可自定义的边框颜色。我受到另一个 SO 帖子的启发来追求这个......这比我预期的要棘手。 要在设置边框大小时正确重新排列内容,请调用 PerformLayout。在 OnResize 中对 DisplayRectangle 的覆盖和对 SetDisplayRectLocation 的调用导致子控件的正确重新定位。同样,子控件在最左上角时没有预期的“0,0”……除非边框宽度设置为 0……并且 OnPaint 提供边框的自定义绘图。

祝你好运!制作作为父级的自定义控件很棘手,但并非不可能。

[Designer(typeof(ParentControlDesigner))]
public partial class CustomPanel : UserControl
{
    Color _borderColor = Color.Blue;
    int _borderWidth = 5;

    public int BorderWidth
    {
        get { return _borderWidth; }
        set { _borderWidth = value; 
            Invalidate();
            PerformLayout();
        }
    }

    public CustomPanel()  { InitializeComponent(); }

    public override Rectangle DisplayRectangle
    {
        get 
        { 
            return new Rectangle(_borderWidth, _borderWidth, Bounds.Width - _borderWidth * 2, Bounds.Height - _borderWidth * 2); 
        }
    }

    public Color BorderColor
    {
        get { return _borderColor; }
        set { _borderColor = value; Invalidate(); }
    }

    new public BorderStyle BorderStyle
    {
        get { return _borderWidth == 0 ? BorderStyle.None : BorderStyle.FixedSingle; }
        set  { }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaintBackground(e);
        if (this.BorderStyle == BorderStyle.FixedSingle)
        {
            using (Pen p = new Pen(_borderColor, _borderWidth))
            { 
                Rectangle r = ClientRectangle; 
                // now for the funky stuff...
                // to get the rectangle drawn correctly, we actually need to 
                // adjust the rectangle as .net centers the line, based on width, 
                // on the provided rectangle.
                r.Inflate(-Convert.ToInt32(_borderWidth / 2.0 + .5), -Convert.ToInt32(_borderWidth / 2.0 + .5));
                e.Graphics.DrawRectangle(p, r);
            }
        }
    }

    protected override void OnResize(EventArgs e)
    {
        base.OnResize(e);
        SetDisplayRectLocation(_borderWidth, _borderWidth);
    }
}

关于c# - 我想让面板有一个粗边框。我能以某种方式设置它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1852829/

相关文章:

c# - 为什么我不能在拥有私有(private)构造函数时调用默认构造函数?

c# - 语音合成器文本到语音作为输入,即通过麦克风

c# - 调试 Windows 窗体应用程序 C# 添加监视

visual-studio - 在 Visual Studio 中关闭自动格式化

c# - Program Files 中的文件夹上的 Directory.Exists 失败

c# - 如何从 c# visual studio 2012 中的 endregion 标记跳转到区域 header ?

c# - 关闭表单按钮事件

visual-studio-2008 - Wix 不会删除 VS 2008 中卸载时的快捷方式

c# - 有没有在解决方案的基础上#define CONSTANT?

C# 如何处理多种消息类型?