【发布时间】:2020-06-24 02:50:21
【问题描述】:
我有以下从 MaskedTextBox 派生的类。
当输入的文本长度小于预定义文本(000000000000,长度为 12)时,我想用红色突出显示文本,否则用绿色突出显示。
在我的自定义 MaskedTextBox 类中,如果输入文本的长度不是 12(无效),我会尝试在 OntextChange 方法覆盖中将文本颜色更改为红色或绿色。
但是我写的代码不起作用。
颜色始终为红色,不会改变。
public partial class MFMaskedTextBox : System.Windows.Forms.MaskedTextBox
{
private int lengthdefaultetext;
protected override void OnCreateControl()
{
base.OnCreateControl();
this.Mask = "0000-0000-0000";
this.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.Font = new System.Drawing.Font("Arial", 16);
this.TextMaskFormat = System.Windows.Forms.MaskFormat.ExcludePromptAndLiterals;
this.Text = "000000000000";
lengthdefaultetext = this.Text.Length;
this.ForeColor= System.Drawing.Color.Red;
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
if (this.Text.Length != lengthdefaultetext)
{
this.ForeColor= System.Drawing.Color.Red;
}
else
{
this.ForeColor = System.Drawing.Color.Green;
}
}
protected override void OnClick(EventArgs eventargs) {
base.OnClick(eventargs);
this.Text = "";
}
}
【问题讨论】:
-
在文本框中输入什么值?当您在文本框中输入 2 个字符时,它会变为红色吗?
-
我只是输入数字。由于这条线,颜色是红色的。(this.ForeColor= System.Drawing.Color.Red;)并且不会改变。看来 this.ForeColor= System.Drawing.Color.Red;不能完全工作。
-
看来 this.ForeColor= System.Drawing.Color.Red;在 textchangeevent 函数中不能完全工作。
标签: c# winforms maskedtextbox