次のように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でこれをどのように達成できますか?