我想验证 TextBox 只允许 1 个小数点和最多 2 位小数位。仅对于数字验证,我正在使用 InputScope="Number",但它无法避免粘贴字母,所以我也需要对粘贴进行任何验证(或者只是禁用粘贴)。例如,用户必须能够插入 23、23.1、23.12 等数字,而不是 23.123、23.1.2 等。
private void tb1_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key >= Windows.System.VirtualKey.Number0 && e.Key <= Windows.System.VirtualKey.Number9 || e.Key == Windows.System.VirtualKey.Decimal || e.Key == Windows.System.VirtualKey.GamepadY)
{
string strkey = e.Key.ToString().Substring(e.Key.ToString().Length - 1, e.Key.ToString().Length - (e.Key.ToString().Length - 1));
if (e.Key >= Windows.System.VirtualKey.Number0 && e.Key <= Windows.System.VirtualKey.Number9)
{
TextBox tb = sender as TextBox;
int cursorPosLeft = tb.SelectionStart;
int cursorPosRight = tb.SelectionStart + tb.SelectionLength;
string result1 = tb.Text.Substring(0, cursorPosLeft) + strkey + tb.Text.Substring(cursorPosRight);
string[] parts = result1.Split('.');
if (parts.Length > 1)
{
if (parts[1].Length > 2 || parts.Length > 2)
{
e.Handled = true;
}
}
}
if (((TextBox)sender).Text.Contains(".") && e.Key == Windows.System.VirtualKey.Decimal)
{
e.Handled = true;
}
}
else
{
e.Handled = true;
}
if (e.Key >= Windows.System.VirtualKey.A && e.Key <= Windows.System.VirtualKey.Z ||
e.Key == Windows.System.VirtualKey.Space)
{
e.Handled = true;
}
}