WinForms自定义控件设计器打开时触发"对象引用未设置为实例"错误
修复WinForms自定义控件设计器“对象引用未设置为实例”异常
在C# WinForms开发场景中,通过「项目>添加组件>自定义控件(Windows Forms)」路径创建新自定义控件后,打开该控件设计器时触发**"object reference not set to an instance of an object"**错误。
错误调用堆栈:
at Microsoft.DotNet.DesignTools.Protocol.Endpoints.Sessions.InitializeRootComponentHandler.HandleRequest(InitializeRootComponentRequest request)
at Microsoft.DotNet.DesignTools.Protocol.Endpoints.RequestHandler`2.Microsoft.DotNet.DesignTools.Protocol.Endpoints.IRequestHandler.HandleRequest(Request request)
Designer.cs 自动生成代码
partial class BKSlide2 { /// <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() { components = new System.ComponentModel.Container(); } #endregion }
自定义控件类代码
public partial class BKSlide2 : Control { public BKSlide2() { InitializeComponent(); } protected override void OnPaint(PaintEventArgs pe) { base.OnPaint(pe); } }
注:对应的.resx文件无任何内容,所有代码均为自动生成,尝试移除InitializeComponent和OnPaint方法后问题仍未改善。
修复方案
以下几种方法可尝试解决该设计器异常:
- 检查.NET SDK版本兼容性:该错误常见于.NET 6+ WinForms设计器的版本匹配问题,确保安装的.NET SDK与Visual Studio版本兼容(例如VS2022需搭配.NET 6/7/8正式版,避免使用预览版SDK)。
- 清理并重建项目:
- 关闭Visual Studio
- 删除项目目录下的
bin、obj文件夹 - 重新打开项目,依次执行生成>清理解决方案、生成>生成解决方案
- 重置Visual Studio设计器缓存:
- 关闭所有VS实例
- 删除以下目录的缓存文件:
%LOCALAPPDATA%\Microsoft\VisualStudio\<版本号>\Designer\ShadowCache%LOCALAPPDATA%\Microsoft\VisualStudio\<版本号>\ComponentModelCache
- 重启VS后重新打开设计器
- 修改自定义控件基类:尝试将基类从
Control改为UserControl,部分场景下设计器对UserControl的支持更稳定,修改后重新生成项目再打开设计器。 - 调整设计器进程模式:在Visual Studio中依次打开工具>选项>Windows Forms设计器,将设计器进程设置为共享(默认可能为隔离),重启VS后测试。
内容的提问来源于stack exchange,提问作者Bob Krauth
相关产品推荐
相关产品推荐

