WPF里如何屏蔽数字以外的字符,只允许输入数字(或者小数点)

这段代码是为了解决WPF里如何屏蔽数字以外的字符,只允许输入数字(或者小数点)的问题。

在。cs源文件添加如下事件之后,再把事件附加到要应用的Textbox里上。具体就是点击Textbox,在右下角切换到Events这个tab页面里,选择相应的KeyDown事件和TextChanged事件。

#region Added by Will for TextBox: Numbers input only 屏蔽数字以外的字符
private void TextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
TextBox txt = sender as TextBox;

//屏蔽非法按键
if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal)
{
//if (txt.Text.Contains(“.”) && e.Key == Key.Decimal)
if (e.Key == Key.Decimal)
{
e.Handled = true;
return;
}
e.Handled = false;
}
else if (((e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
{
//if (txt.Text.Contains(“.”) && e.Key == Key.OemPeriod)
if (e.Key == Key.OemPeriod)
{
e.Handled = true;
return;
}
e.Handled = false;
}
else
{
e.Handled = true;
}
}

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
//屏蔽中文输入和非法字符粘贴输入
TextBox textBox = sender as TextBox;
TextChange[] change = new TextChange[e.Changes.Count];
e.Changes.CopyTo(change, 0);

int offset = change[0].Offset;
if (change[0].AddedLength > 0)
{
double num = 0;
if (!Double.TryParse(textBox.Text, out num))
{
textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength);
textBox.Select(offset, 0);
}
}
}
#endregion

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>