我可以确保用户只能在WPF中的KeyDown事件的文本框中输入字母数字和空格吗?不允许使用特殊字符。
答案 0 :(得分:6)
检查文本框的keydown事件并按
进行操作 // If escape is presses, then close the window.
if( Key.Escape == e.Key )
{
this.Close();
}
// Allow alphanumeric and space.
if( e.Key >= Key.D0 && e.Key <= Key.D9 ||
e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9 ||
e.Key >= Key.A && e.Key <= Key.Z ||
e.Key == Key.Space )
{
e.Handled = false;
}
else
{
e.Handled = true;
}
// If tab is presses, then the focus must go to the
// next control.
if( e.Key == Key.Tab )
{
e.Handled = false;
}
希望这会有所帮助......
答案 1 :(得分:2)
您还可以使用文本框的PreviewTextInput事件。
<TextBox Name="txtName" PreviewTextInput="txtName_PreviewTextInput"/>
在您的代码中添加以下内容:
private void txtName_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
foreach (char c in e.Text)
{
if (!char.IsLetterOrDigit(c))
{
e.Handled = true;
break;
}
}
}
答案 2 :(得分:0)
KeyDown事件处理程序可能不是执行此操作的最佳位置,因为该字符已添加到TextBox中。您可以响应PreviewKeyDown事件并阻止事件继续,但这可能会产生未知后果。
一种方法是将ValidationRule附加到TextBox。虽然这不会阻止用户输入字符,但它会通知他们不允许这样做。要做到这一点,你从System.Windows.Controls.ValidationRule派生得到这样的东西:
public class MyValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
// Logic to determine if the TextBox contains a valid string goes here
// Maybe a reg ex that only matches alphanumerics and spaces
if(isValidText)
{
return ValidationResult.ValidResult;
}
else
{
return new ValidationResult(false, "You should only enter an alphanumeric character or space");
}
}
}
然后在XAML中使用它:
<TextBox>
<TextBox.Text>
<Binding Path="MyString"
UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<myns:MyValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
每次用户输入无效字符时,他们都会收到错误消息。希望有一些用处。
答案 3 :(得分:0)
我认为使用KeyDown是一个很好的做法。 退回是您还必须处理Backspace,删除和Tab键。
相反: 处理PreviewTextInput
private void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!IsMatch(e.Text)) e.Handled = true;
}
private bool IsMatch(string input)
{
return Regex.IsMatch(input, MyRegexString);
}
然后必须照顾PasteHandler: 在构造函数中添加以下行。
DataObject.AddPastingHandler(TargetTextBoxName, PasteHandler);
private void PasteHandler(object sender, DataObjectPastingEventArgs e)
{
if (!e.DataObject.GetDataPresent(typeof(string))) return;
// Allow pasting only numeric
var pasteText = e.DataObject.GetData(typeof(string)) as string;
if (!IsMatch(pasteText))
{
e.CancelCommand();
}
}