【发布时间】:2014-05-19 19:04:44
【问题描述】:
在Windows Forms 和C# 中,我继承自TextBox 类。我覆盖了 TextBox 中的 Text 属性。一切顺利,直到我尝试使用 TextChanged 事件。 OnTextChanged 事件在此处无法正常工作,因为未调用 Text.set 属性。
Initial field content 123, txpText.Text = 123
Field content changed to a , txpText.Text still 123
Field content changed to aa , txpText.Text still 123
Field content changed to aaa , txpText.Text still 123
这是我的自定义文本框代码
public class ShowPartialTextBox : System.Windows.Forms.TextBox
{
private string _realText;
public override string Text
{
get { return _realText; }
set // <--- Not invoked when TextChanged
{
if (value != _realText)
{
_realText = value;
base.Text = _maskPartial(_realText);
//I want to make this _maskPartial irrelevant
}
}
}
protected override void OnTextChanged(EventArgs e)
{
//Always called. Manually invoke Text.set here? How?
base.OnTextChanged(e);
}
private string _maskPartial(string txt)
{
if (txt == null)
return string.Empty;
if (_passwordChar == default(char))
return txt;
if (txt.Length <= _lengthShownLast)
return txt;
int idxlast = txt.Length - _lengthShownLast;
string result = _lpad(_passwordChar, idxlast) + txt.Substring(idxlast);
return result;
}
}
这是表单类
public partial class Form1 : Form
{
private ShowPartialTextBox txpText;
private void InitializeComponent()
{
txpText = new ShowPartialTextBox();
txpText.Text "123";
txpText.TextChanged += new System.EventHandler(this.txpText_TextChanged);
}
private void txpText_TextChanged(object sender, EventArgs e)
{
label1.Text = txpText.Text; //always shows 123
}
}
我使用 _maskPartial。它正在更改显示的文本,同时仍保留其真实内容。我希望这个自定义文本框“几乎”模拟 PasswordChar 属性,并显示最后 x 个字符。
【问题讨论】: