C#中的数字文本框 – WPF

我想在WPF中创建一个只接受数字的文本框…我已经重新申请并且人们说使用按键事件或屏蔽文本框,但它们是在Windows窗体中…

对于WPF:

private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e) { if (!char.IsDigit(e.Text, e.Text.Length - 1)) e.Handled = true; } 

对于Windows窗体:

 private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsDigit(e.KeyChar) ) e.Handled = true; }