控件属性:
禁用中文输入法
<Grid>
<TextBox HorizontalAlignment="Left" Margin="69,217,0,0" Text="" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" KeyDown="TextBox_KeyDown" PreviewTextInput="TextBox_PreviewTextInput" InputMethod.IsInputMethodEnabled="False"/>
</Grid>
事件(不使用正则表达式):
按键事件:
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if ((e.Key == Key.OemPeriod || e.Key == Key.OemMinus || e.Key == Key.Decimal || e.Key == Key.Subtract) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
{
e.Handled = false;
}//允许大小键盘的“.”和“-”输入
else if (((int)e.Key) >= 74 && ((int)e.Key) <= 84)
{
e.Handled = false;
}//允许小键盘数字输入
else if (((int)e.Key) >= 34 && ((int)e.Key) <= 43 && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
{
e.Handled = false;
}//允许大键盘数字输入
else
e.Handled = true;
}
文本输入事件:
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
var textelem = (sender as TextBox);
if (textelem.Text.StartsWith("0") && textelem.Text.Length == 1)
{
if (e.Text == "0")
{
e.Handled = true;
return;
}
else if (e.Text == ".")
{
e.Handled = false;
}
else
textelem.Text = "";
}
if (textelem.Text.Length == 0 && e.Text == ".")
{
e.Handled = true;
textelem.Text = "0.";
textelem.SelectionStart = textelem.Text.Length;
return;
}
if ((string.IsNullOrWhiteSpace(textelem.Text) || textelem.Text.Contains(".")) && e.Text == ".")
{
e.Handled = true;
return;
}
if (textelem.Text.Length > 0 && e.Text == "-")
{
e.Handled = true;
return;
}
}