将PasswordChar属性实现到支持占位符的自定义C#Windows窗体TextBox类

时间:2014-01-03 10:35:52

标签: c# winforms textbox passwords placeholder

我正在尝试将PasswordChar属性实现到与我的Placeholder类配合的TextBox类。这是我的代码:

class MyTextBox : TextBox
{
    public Placeholder Placeholder;

    public MyTextBox()
    {
        Placeholder = new Placeholder(this);

        GotFocus += new EventHandler(_GotFocus);
        LostFocus += new EventHandler(_LostFocus);
    }

    private void _GotFocus(object sender, EventArgs e)
    {
        Placeholder.Active = false;
    }

    private void _LostFocus(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(Text))
            Placeholder.Active = true;
    }
}

class Placeholder
{
    private MyTextBox textBox;
    private bool active = false;
    public bool Active
    {
        get { return active; }
        set
        {
            if (value)
            {
                textBox.ForeColor = ForeColor;
                textBox.Text = Text;
            }
            else if (active && !value)
            {
                textBox.ForeColor = previousForeColor;
                textBox.Text = string.Empty;
            }

            active = value;
        }
    }
    private Color previousForeColor;
    private Color foreColor = Color.Gray;
    public Color ForeColor
    {
        get { return foreColor; }
        set
        {
            previousForeColor = ForeColor;
            ForeColor = value;
        }
    }
    private string text = "Placeholder";
    public string Text
    {
        get { return text; }
        set
        {
            text = value;

            if (active)
                textBox.Text = Text;
        }
    }

    public Placeholder(MyTextBox textBox)
    {
        this.textBox = textBox;
    }
}

我希望它工作的方式是,如果我将TextBox的属性PasswordChar设置为除了'\ 0'以外的任何内容,那么当TextBox的属性的占位符属性Active为true时应将其设置为'\ 0',并且应该将其设置为当密码被设置为假时,无论密码是什么。 换句话说,如果设置了PasswordChar,则在Active属性为true时取消屏蔽文本,并在文本设置回false时重新屏蔽该文本。

1 个答案:

答案 0 :(得分:0)

这听起来就像将原始PasswordChar存储在临时变量中一样简单:

class Placeholder
{
    private MyTextBox textBox;
    private bool active = false;
    private char? originalPasswordChar = null;
    public bool Active
    {
        get { return active; }
        set
        {
            if (value)
            {
                textBox.ForeColor = ForeColor;
                textBox.Text = Text;
                if (originalPasswordChar == null) originalPasswordChar = textBox.PasswordChar;
            }
            else if (active && !value)
            {
                textBox.ForeColor = previousForeColor;
                textBox.Text = string.Empty;
                textBox.PasswordChar = originalPasswordChar.Value;
                originalPasswordChar = null; 
            }

            active = value;
        }
    }
    // (...)
}