[英]C# Custom Control's attribute not initialized after InitializeComponent() call?
I'm trying to create a simple textbox that shows a hint text when it's not focused and its text is empty, and hides the hint text when it's focused.我正在尝试创建一个简单的文本框,它在未聚焦且文本为空时显示提示文本,并在聚焦时隐藏提示文本。 To do that, I created a Custom Control by extending TextBox.为此,我通过扩展 TextBox 创建了一个自定义控件。
public partial class HintedTextBox : TextBox
{
private Color foreColor;
public HintedTextBox()
{
InitializeComponent();
foreColor = ForeColor;
GotFocus += OnFocused;
LostFocus += OnFocusLost;
OnFocusLost(null, null); // Problem
}
public string Hint { get; set; }
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
private void OnFocused(object sender, EventArgs e)
{
if (Text == Hint)
{
Text = "";
ForeColor = foreColor;
}
}
private void OnFocusLost(object sender, EventArgs e)
{
if (Text.Trim() == "")
{
Text = Hint;
ForeColor = Color.Gray;
}
else
{
ForeColor = foreColor;
}
}
}
Logically, I would need to call the OnFocusLost()
procedure after the component is initialized so the app will show the hint when the Form is first shown.从逻辑上讲,我需要在组件初始化后调用OnFocusLost()
过程,以便应用程序在首次显示表单时显示提示。 The problem is at the line I marked with // problem
.问题出在我用// problem
标记的那一行。 At this line, both my custom attribute Hint
and the stock attribute Text
are both not initialized, even if I've set their values in the Designer.在这一行,我的自定义属性Hint
和股票属性Text
都没有初始化,即使我已经在设计器中设置了它们的值。 The weird thing is that the ForeColor
attribute is already initialized at that line.奇怪的是ForeColor
属性已经在该行初始化。 Is there another Event that fires as soon as these values are initialized, or is there any other solution?一旦这些值被初始化,是否有另一个事件会触发,或者有没有其他解决方案?
I've also tried calling OnFocusLost()
from outside the Control on Windows Form's FormLoad Event.我还尝试从 Windows 窗体的 FormLoad 事件上的控件外部调用OnFocusLost()
。 It doesn't work either.它也不起作用。 The Text
and Hint
are just always empty at the start, even after the InitializeComponent()
call. Text
和Hint
在开始时总是空的,即使在InitializeComponent()
调用之后也是如此。
Thank you for your attention.感谢您的关注。
EDIT: I forgot to attach the Form's on-load Event to my FormLoad()
method, but nonetheless Vladimir Stoyanov's solution worked perfectly and even better.编辑:我忘记将 Form 的加载事件附加到我的FormLoad()
方法,但 Vladimir Stoyanov 的解决方案仍然完美甚至更好。
As an option you can just use setter of the Hint property.作为一种选择,您可以只使用 Hint 属性的 setter。 It will handle the cases when you need to change your Hint programmatically later当您稍后需要以编程方式更改提示时,它将处理这些情况
private string hint;
public string Hint
{
get => hint;
set
{
hint = value;
OnFocusLost(null, null);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.