添加预览文本输入事件。像这样:<Text@R_421_2419@ PreviewTextInput="PreviewTextInput" />
。
然后在该设置内,e.Handled
如果不允许输入文本。e.Handled = !IsTextAllowed(e.Text);
我在IsTextAllowed
方法中使用了一个简单的正则表达式,以查看是否应该允许他们键入内容。就我而言,我只想允许数字,点和破折号。
private static readonly Regex _regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
private static bool IsTextAllowed(string text)
{
return !_regex.IsMatch(text);
}
如果你想防止不正确的数据勾起来了的粘贴DataObject.Pasting
事件DataObject.Pasting="Text@R_421_2419@Pasting"
如在这里(代码摘录):
// Use the DataObject.Pasting Handler
private void Text@R_421_2419@Pasting(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();
}
}