我通过继承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实现这个?