【问题标题】:How to correctly override the TextBox.Text property如何正确覆盖 TextBox.Text 属性
【发布时间】: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 个字符。

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    在 Text 属性设置器上设置断点时很容易看到。您假设在文本框中键入将调用 setter。它没有。一种解决方法是:

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

    但是您必须使用 _maskPartial() 来完成这项工作,这肯定不是无关紧要的。

    【讨论】:

    • 您的问题是正确的。在 TextBox 中键入不会自动调用 setter。我不能使用 _realText = base.Text 因为 base.Text 已经包含更改的显示文本。本质上我想要 Text = _realText + base.Text 的变化
    • 我添加了 _maskPartial()。一个目标是让这无关紧要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 2011-05-29
    • 2011-11-06
    • 2015-01-08
    • 2013-12-16
    • 1970-01-01
    相关资源
    最近更新 更多