正如标题所说的那样.我已经看过继承TextBox,但唯一明智的覆盖是"OnKeyDown",但这只是给我一个Key枚举的密钥(无法使用Char.IsNumeric()).
我接受了Nidhal建议的答案并对其进行了一些编辑以处理数字上方字符的移位情况(即!@#$%^&*()),因为该解决方案仍然允许文本框中的这些字符.
private void NumClient_KeyDown(object sender, KeyEventArgs e) { // Handle Shift case if (Keyboard.Modifiers == ModifierKeys.Shift) { e.Handled = true; } // Handle all other cases if (!e.Handled && (e.Key < Key.D0 || e.Key > Key.D9)) { if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9) { if (e.Key != Key.Back) { e.Handled = true; } } } }
访问http://www.dataartist.net/blog/post/Silverlight-Behavior-Modifications-13-NumericOnlyBehavior.aspx或使用TextBox行为,如下所示
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Interactivity; namespace DataArtist { public class NumericOnly : Behavior{ private string Text { get; set; } private bool shiftKey; public bool StripOnExit { get; set; } public NumericOnly() { StripOnExit = false; } protected override void OnAttached() { base.OnAttached(); AssociatedObject.KeyDown += KeyDown; AssociatedObject.KeyUp += KeyUp; AssociatedObject.GotFocus += GotFocus; AssociatedObject.LostFocus += LostFocus; } void KeyUp(object sender, KeyEventArgs e) { if (e.Key == Key.Shift) { shiftKey = false; } } void KeyDown(object sender, KeyEventArgs e) { if (StripOnExit != false || e.Key == Key.Tab || e.Key == Key.Enter) { return; } if (e.Key == Key.Shift) { shiftKey = true; } else { if (IsNumericKey(e.Key) == false) { e.Handled = true; } } } void GotFocus(object sender, RoutedEventArgs e) { Text = AssociatedObject.Text; } private void LostFocus(object sender, RoutedEventArgs e) { if (AssociatedObject.Text == Text) { return; } string content = string.Empty; foreach (var c in AssociatedObject.Text) { if (Char.IsNumber(c) == true) { content += c; } } AssociatedObject.Text = content; } public bool IsNumericKey(Key key) { if (shiftKey == true) { return false; } string code = key.ToString().Replace("NumPad", "D"); if (code[0] == 'D' && code.Length > 1) { return (Char.IsNumber(code[1])); } return false; } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.KeyDown -= KeyDown; AssociatedObject.LostFocus -= LostFocus; AssociatedObject.GotFocus -= GotFocus; } } }
private void Numclient_KeyDown(object sender, KeyEventArgs e) { if (e.Key < Key.D0 || e.Key > Key.D9) { if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9) { if (e.Key != Key.Back && e.Key != Key.Shift) { e.Handled = true; } } } }
请查看Toolkit http://codeplex.com/Silverlight中的NumericUpDown,也许您可以使用它或查看源代码来实现您自己的数字文本框.