![](/img/trans.png)
[英]How to override MVC2 model value for model property for Textbox.Text value
[英]How to correctly override the TextBox.Text property
在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
這是我的自定義TextBox代碼
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;
}
}
這是Form類
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。 它正在改變顯示的文本,同時仍然保留其真實內容。 我希望這個自定義TextBox“幾乎”模擬PasswordChar屬性,顯示最后x個字符。
在Text屬性設置器上設置斷點時很容易看到。 您假設在文本框中鍵入將調用setter。 它沒有。 一個解決方法是:
protected override void OnTextChanged(EventArgs e) {
_realText = base.Text;
base.OnTextChanged(e);
}
但你必須使用_maskPartial()來完成它,它肯定不是無關緊要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.