c# - 设计器中的自定义控件未处理的异常

标签 c# winforms visual-studio

我正在使用我在网上找到的自定义选项卡控件的代码,并对其进行了修改以满足我的需要。

protected override void OnPaint(PaintEventArgs e) {
    this.PaintTransparentBackground(e.Graphics, this.ClientRectangle);
    this.PaintAllTabs(e);

    if (this.TabCount > 0 && ShowUnderline)
        e.Graphics.DrawLine(new Pen(Colors.TAB_SELECTED, 1), UnderlineStartOffset, 23, this.ClientRectangle.Width - UnderlineEndOffset, 23);
}

protected void PaintAllTabs(PaintEventArgs e) {
    if (this.TabCount > 0)
    {
        CursorSet = false;

        for (int index = this.TabCount - 1; index > -1; index--)
        {
            this.PaintTab(e, index);
            this.PaintTabText(e, index);
            this.TabPages[index].BackColor = Colors.CUSTOM_BLACK_2;
        }
    }
}

我还添加了一些可在设计器中编辑的属性(不确定这是否是其应有的方式):

    [Browsable(true)]
    [Category("Customizations")]
    [DisplayName("Tab X Offset")]
    public int XOffset { get; set; }

    [Browsable(true)]
    [Category("Customizations")]
    [DisplayName("Tab Y Offset")]
    public int YOffset { get; set; }

    [Browsable(true)]
    [Category("Customizations")]
    [DisplayName("Tab Width Offset")]
    public int WOffset { get; set; }

    [Browsable(true)]
    [Category("Customizations")]
    [DisplayName("Show Tab Underline")]
    public bool ShowUnderline { get; set; }

    [Browsable(true)]
    [Category("Customizations")]
    [DisplayName("Underline Start Offset")]
    public int UnderlineStartOffset { get; set; }

    [Browsable(true)]
    [Category("Customizations")]
    [DisplayName("Underline End Offset")]
    public int UnderlineEndOffset { get; set; }

    [Browsable(true)]
    [Category("Customizations")]
    [DisplayName("Enable Tab Closing")]
    public bool EnableTabClosing { get; set; }

结果是,它在设计器中和运行时看起来都很棒,前提是在运行时未选择设计器。如果是,我会收到以下错误:

The control App.Custom_Controls.CustomTabControl has thrown an unhandled exception in the designer and has been disabled.

Exception: The file ..\View_Main.cs cannot be modifed in the designer while building or debugging.

如果我用 OnPaint 包围

if(!this.DesignMode) { }

错误已解决,但我在设计器中丢失了选项卡控件的绘制。

最佳答案

不要这样做:

this.TabPages[index].BackColor = Colors.CUSTOM_BLACK_2;

在绘画事件中。绘制事件仅用于绘制,不用于设置属性。

关于c# - 设计器中的自定义控件未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29705167/

相关文章:

c# - 循环两次触发插入语句

c# - 适用于 Windows Phone 8.1 Silverlight 的数据库

c# - 在 Click 事件中从 TextBox 中选择文本

c# - Xaml 不是破坏了我的封装吗?

c# - 如何绘制Windows经典风格的窗口元素

git - 在 Visual Studio 17 git 中修剪分支?

c++ - 在 Visual Studio C++ 调试 session 期间找出当前目录

c# - 表示数字的最少位数

c# - Windows 窗体标签页事件

c - Visual Studio 2012是否适合C(不是C++)专业编程?