You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Visual Studio设计器中预览WinForms非UserControl自定义控件?

WinForms自定义控件设计器渲染问题

我按照微软官方教程创建了一个继承自Button(而非UserControl)的WinForms自定义控件,遇到以下问题:

  • 打开该控件的设计器视图时,无法看到控件的渲染效果,仅显示黑色背景及提示文字:

    "To add components to your class, drag them from the Toolbox and use the Properties window to set their properties. To create methods and events for your class, switch to code view."
    Visual Studio设计器标签页截图

  • 将该自定义控件添加到窗体后,窗体的设计器能正常渲染它:
    Visual Studio窗体可视化设计器中正常渲染的自定义控件截图

自定义控件代码如下:

public partial class CustomControl1 : Button
{
    private int _counter = 0;

    public CustomControl1()
    {
        InitializeComponent();
    }

    protected override void OnPaint(PaintEventArgs pe)
    {
        // Draw the control
        base.OnPaint(pe);

        // Paint our string on top of it
        pe.Graphics.DrawString($"Clicked {_counter} times", Font, Brushes.Purple, new PointF(3, 3));
    }

    protected override void OnClick(EventArgs e)
    {
        // Increase the counter and redraw the control
        _counter++;
        Invalidate();

        // Call the base method to invoke the Click event
        base.OnClick(e);
    }
}

partial class CustomControl1
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }

        base.Dispose(disposing);
    }

    #region Component Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify 
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        SuspendLayout();
        ResumeLayout(false);
    }

    #endregion
}

这是Visual Studio设计器的限制吗?需要修改什么才能在控件自身的设计器视图中看到渲染效果?

内容的提问来源于stack exchange,提问作者Heltta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 03:15:00