WPF中的自定义控件:创建数字PasswordBox

时间:2012-02-06 18:38:37

标签: wpf textbox user-controls passwordbox

我通过继承TextBox创建了一个数字TextBox,如下所示:

public class NumericTextBox : TextBox
{
    public NumericTextBox() : base()
    {
        this.AddHandler(DataObject.PastingEvent, new DataObjectPastingEventHandler(this.TextBoxPasting));
    }

    protected override void OnPreviewTextInput(TextCompositionEventArgs e)
    {
        base.OnPreviewTextInput(e);
        e.Handled = !IsTextAllowed(e.Text);
    }

    private bool IsTextAllowed(string text)
    {
        Regex regex = new Regex("[^0-9]+");
        return !regex.IsMatch(text);
    }

    private void TextBoxPasting(object sender, DataObjectPastingEventArgs e)
    {
        if (e.DataObject.GetDataPresent(typeof(String)))
        {
            String text = (String)e.DataObject.GetData(typeof(String));
            if (!IsTextAllowed(text))
            {
                e.CancelCommand();
            }
        }
        else
        {
            e.CancelCommand();
        }
    }
}

但我不能对PasswordBox做同样的事情,因为密码框是一个密封的类。 任何想法我怎么能为PasswordBox实现这个?

0 个答案:

没有答案