如何重写UserControl类以绘制自定义边框? [英] How to override UserControl class to draw a custom border?

查看:164
本文介绍了如何重写UserControl类以绘制自定义边框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重写System.Windows.Forms.UserControl来绘制自定义边框(例如,使用自定义颜色)。不一定要使用内置的类,因为可以影响边框行为的唯一方法/属性是BorderStyle。

I would like to override System.Windows.Forms.UserControl to draw a custom border (e.g. using custom color). It's not possiblу to do usign built-in classes, because the only method/property you can affect the border behavior is BorderStyle.

按以下方式重写OnPaint(下面的代码)并不是一个好的解决方案,因为它基本上是在原始边框之上绘制另一个边框。

Overriding OnPaint the following way (code below) is not a good solution, because it's basically drawing another border on top of original one.

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        if (this.BorderStyle == BorderStyle.FixedSingle)
            ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, Color.LightGray, ButtonBorderStyle.Solid);
    }

有人知道如何在自定义控件中覆盖边框绘制吗?

Does anyone know how to override border drawing in custom control?

出于某些原因,在我的情况下,不能将此用户控件放入面板中。

Putting this user control into a panel is not an option in my case for certain reasons.

推荐答案

将base.BorderStyle设置为None不会绘制默认边框。您需要重写BorderStyle属性才能使其正常工作。

Set base.BorderStyle to None to the default border isn't drawn. You'll need to override the BorderStyle property to make this work.

    public UserControl1() {
        InitializeComponent();
        base.BorderStyle = BorderStyle.None;
        this.BorderStyle = BorderStyle.FixedSingle;
    }

    private BorderStyle border;

    public new BorderStyle BorderStyle {
        get { return border; }
        set {
            border = value;
            Invalidate();
        }
    }

这篇关于如何重写UserControl类以绘制自定义边框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆