我不熟悉NumericTextBox
,但这是一个简单的 C#/XAML 实现,它只允许数字和十进制字符。
它所做的只是覆盖OnKeyDown
事件;根据被按下的键,它允许或不允许事件到达基TextBox
类。
我应该注意,此实现适用于 Windows 应用商店应用程序 - 我相信您的问题是关于该类型的应用程序,但我不是 100% 确定。
public class MyNumericTextBox : TextBox
{
protected override void OnKeyDown(KeyRoutedEventArgs e)
{
HandleKey(e);
if (!e.Handled)
base.OnKeyDown(e);
}
bool _hasDecimal = false;
private void HandleKey(KeyRoutedEventArgs e)
{
switch (e.Key)
{
// allow digits
// TODO: keypad numeric digits here
case Windows.System.VirtualKey.Number0:
case Windows.System.VirtualKey.Number1:
case Windows.System.VirtualKey.Number2:
case Windows.System.VirtualKey.Number3:
case Windows.System.VirtualKey.Number4:
case Windows.System.VirtualKey.Number5:
case Windows.System.VirtualKey.Number6:
case Windows.System.VirtualKey.Number7:
case Windows.System.VirtualKey.Number8:
case Windows.System.VirtualKey.Number9:
e.Handled = false;
break;
// only allow one decimal
// TODO: handle deletion of decimal...
case (Windows.System.VirtualKey)190: // decimal (next to comma)
case Windows.System.VirtualKey.Decimal: // decimal on key pad
e.Handled = (_hasDecimal == true);
_hasDecimal = true;
break;
// pass various control keys to base
case Windows.System.VirtualKey.Up:
case Windows.System.VirtualKey.Down:
case Windows.System.VirtualKey.Left:
case Windows.System.VirtualKey.Right:
case Windows.System.VirtualKey.Delete:
case Windows.System.VirtualKey.Back:
case Windows.System.VirtualKey.Tab:
e.Handled = false;
break;
default:
// default is to not pass key to base
e.Handled = true;
break;
}
}
}
这是一些示例 XAML。请注意,它假定MyNumericTextBox
位于项目名称空间中。
<StackPanel Background="Black">
<!-- custom numeric textbox -->
<local:MyNumericTextBox />
<!-- normal textbox -->
<TextBox />
</StackPanel>