Aggiungi un evento di inserimento del testo di anteprima. Mi piace così: <TextBox PreviewTextInput="PreviewTextInput" />
.
Poi all'interno che impostare l'e.Handled se il testo non è permesso.
e.Handled = !IsTextAllowed(e.Text);
Io uso una semplice espressione regolare in IsTextAllowed per vedere se devo permettere quello che hanno digitato. Nel mio caso voglio solo consentire numeri, punti e trattini.
private static bool IsTextAllowed(string text)
{
Regex regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
return !regex.IsMatch(text);
}
Se si desidera impedire l'incollatura dei dati non corretti collegare l'evento DataObject.Pasting DataObject.Pasting="TextBoxPasting"
come mostrato di seguito (codice estratto):
// Use the DataObject.Pasting Handler
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();
}
}
fonte
2015-07-28 12:56:00
Quindi vuoi dire un numero intero positivo o negativo, come 1234 o -1234 O vuoi dire qualcosa che ha un segno - in esso, come 800-555-5555 ""? –