基本原理是直接添加两个事件,然后加上判断:
1. KeyDown 2.TextChanged
话不多说,直接上代码:
前台代码:
<TextBox x:Name="TextBoxForText" HorizontalAlignment="Left" Height="101" Margin="10,167,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="299" KeyDown="TextBoxForText_KeyDown" MaxLength="3" TextChanged="TextBoxForText_TextChanged">
后台代码:
private void TextBoxForText_KeyDown(object sender, KeyEventArgs e)
{
TextBox txt = sender as TextBox;
// 过滤按键
if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
{
e.Handled = false;
}
else if (((e.Key >= Key.D0 && e.Key <= Key.D9)))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
private void TextBoxForText_TextChanged(object sender, TextChangedEventArgs e)
{
try
{
string strNum = TextBoxForText.Text;
if ("" == strNum || null == strNum)
{
return;
}
int num = int.Parse(TextBoxForText.Text);
TextBoxForText.Text = num.ToString();
if (num <= 100)
{
return;
}
else
{
TextBoxForText.Text = TextBoxForText.Text.Remove(2);
TextBoxForText.SelectionStart = TextBoxForText.Text.Length;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}