C#:创建触发事件的自定义控件文本框

C#: Create a Custom Control textbox which triggers events

我正在制作一个自定义控件文本框,其中包含 Cue (填充文本)CueColor (填充文本颜色) 个属性。我在文本框内创建了一个 EnterLeave 事件来调节 Cue。然而,当我尝试应用它时,它使我的 IDE 崩溃(Visual Studio 2015,如果这有帮助的话)。

我读过一些有类似问题的帖子: Winforms user controls custom events

虽然我不太确定我的问题是否有相同的解决方案。我如何让它发挥作用?为了清楚起见,这是我的代码:

class CueTextBox : TextBox
    {
        public string Cue
        {
            get { return Cue; }
            set { Cue = value;}
        }

        public Color CueColor
        {
            get { return CueColor; }
            set { CueColor = value; }
        }

        private void CueTextBox_Enter(object sender, EventArgs e)
        {
            TextBox t = sender as TextBox;
            if (t.ForeColor == this.CueColor)
            {
                t.Text = "";
                t.ForeColor = this.ForeColor;
            }
        }

        private void CueTextBox_Leave(object sender, EventArgs e)
        {
            TextBox t = sender as TextBox;
            if (t.Text.Trim().Length == 0)
            {
                t.Text = Cue;
                t.ForeColor = this.CueColor;
            }
        }
    }

我在您的代码中唯一看到的是 属性 定义递归调用自身,这会在将控件添加到设计图面时导致堆栈溢出。

   public string Cue
    {
        get { return Cue; }
        set { Cue = value;}
    }

定义支持字段或使用自动实现的属性。

    private string cue = String.Empty;
    public string Cue
        {
        get { return cue; }
        set { cue = value; }
        }

public string Cue { get; set; }

您的问题暗示添加事件处理程序导致了问题。这有时可能是自定义控件的问题。 Control.DesignMode 属性 是为了允许有条件地执行代码。但是,它不在构造函数中运行。您需要做一些修改以确定 IDE 是否处于活动状态。

此 属性 可用于 Visual Studio 中的开发,作为 DesignMode 的替代方案。

    private bool InDesignMode
        {
        get
            {
            return (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime) || 
                    base.DesignMode || 
                    (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv");
            }
        }

在自定义控件的解决方案开发中是一种自我虐待的练习。您最好转到“项目属性”->“调试”选项卡并将 "Start Action" 设置为 "Start External Program" 并使用 "devenv.exe" 作为程序。当您 "run" 调试器时,这将启动一个新的 VS 实例。将控件添加到新 VS 实例的设计图面时,可以调试控件的代码。将命中断点并显示异常。