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



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

我读过一些有类似问题的帖子: Winforms用户控制自定义事件

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

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");
}
}

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

最新更新