用PreviewKeyDown事件和KeyEventArgs.Handled 来实现
示例:限制了只能输入1和退格键
XAML
<TextBox HorizontalAlignment="Left" Margin="0,60,0,0" Name="textBox1" Width="120" Height="22" VerticalAlignment="Top" PreviewKeyDown="textBox1_PreviewKeyDown" />
C#
private void textBox1_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.D1 && e.Key != Key.Back && e.Key !=Key.NumPad1)
{
e.Handled = true;
}
}
{
if (e.Key != Key.D1 && e.Key != Key.Back && e.Key !=Key.NumPad1)
{
e.Handled = true;
}
}