0

我通过继承 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 实现这一目标吗?

4

0 回答 0