简体   繁体   中英

How to correctly override the TextBox.Text property

In Windows Forms and C#, I am inheriting from the TextBox class. I override the Text property from TextBox. Everything goes well until I try to use the TextChanged event. The OnTextChanged event does not work properly here, as the Text.set property is not invoked.

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

Here is my custom TextBox code

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;
    }
}

Here is the Form class

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
    }
}

I use _maskPartial. It is altering the displayed Text, while still preserving its real content. I want this custom TextBox to "almost" simulate PasswordChar property, with showing the last x characters.

Easy to see when you set a breakpoint on the Text property setter. You assume that typing in the text box will call the setter. It doesn't. One fix is this:

protected override void OnTextChanged(EventArgs e) {
    _realText = base.Text;
    base.OnTextChanged(e);
}

But you'll have to make that work with _maskPartial(), it surely isn't irrelevant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM