我制作了一个自定义的 TextBox
,这样我就可以给它加上边框,效果很好...
问题是我想将 PasswordChar
设置为 *
,但这不起作用
这是我的代码:
public class TextBoxEx : TextBox
{
// The TextBox
private TextBox textBox = new TextBox();
// Border color of the textbox
private Color borderColor = Color.Gray;
// Ctor
public TextBoxEx()
{
this.PasswordChar ='*';
this.Paint += new PaintEventHandler(TextBoxEx_Paint);
this.Resize += new EventHandler(TextBoxEx_Resize);
textBox.Multiline = true;
textBox.BorderStyle = BorderStyle.None;
this.Controls.Add(textBox);
this.UseSystemPasswordChar = true;
InvalidateSize();
}
// Exposed properties of the textbox
public override string Text
{
get { return textBox.Text; }
set { textBox.Text = value; }
}
// ... Expose other properties you need...
// The border color property
public Color BorderColor
{
get { return borderColor; }
set { borderColor = value; Invalidate(); }
}
// Expose the Click event for the texbox
public event EventHandler TextBoxClick
{
add { textBox.Click += value; }
remove { textBox.Click -= value; }
}
// ... Expose other events you need...
private void TextBoxEx_Resize(object sender, EventArgs e)
{
InvalidateSize();
}
private void TextBoxEx_Paint(object sender, PaintEventArgs e)
{
ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, borderColor, ButtonBorderStyle.Solid);
}
private void InvalidateSize()
{
textBox.Size = new Size(this.Width - 2, this.Height - 2);
textBox.Location = new Point(1, 1);
}
}
通常,当我尝试默认设置自定义控件的属性时,它不起作用,例如,如果我设置
this.ReadOnly=true;
这也行不通。所以问题不在 PasswordChar
本身。
有人知道解决方案吗?
最佳答案
由于该类本身继承了 TextBox
类,因此您无需创建内部文本框。
考虑到这一点,您可以取出private TextBox textBox
的声明,并将对该成员的引用替换为this
,因为this
是 TextBox
的后代。
在构造函数中,您还将删除 this.Controls.Add(textBox);
,因为不再有要添加的内部控件。
覆盖的 Text
属性也可以删除,因为它不会向 TextBox
定义添加功能。
InvalidateSize
方法需要重新设计,因为调整 Size
成员会触发 TextBoxEx_Resize
处理程序方法,该方法调用 InvalidateSize
方法,最终导致 StackOverflowException
。
最后一件事,也是一件重要的事。根据MSDN ...
If the Multiline property is set to true, setting the PasswordChar property has no visual effect. When the PasswordChar property is set to true, cut, copy, and paste actions in the control using the keyboard cannot be performed, regardless of whether the Multiline property is set to true or false.
意味着如果文本框是多行的,则不会显示文本框 PasswordCharacter
关于c# - 当我尝试制作自定义文本框时,密码字符不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50749968/