标签:
< Grid > < TextBox Name = "textBox1" PreviewTextInput = "textBox1_PreviewTextInput" HorizontalAlignment = "Stretch" VerticalAlignment = "Center" /> </ Grid > |
1
2
3
4
5
6
|
//using System.Text.RegularExpressions; private void textBox1_PreviewTextInput( object sender, TextCompositionEventArgs e) { Regex re = new Regex( "[^0-9.-]+" ); e.Handled = re.IsMatch(e.Text); } |
KeyDown事件:2011-04-28优化Tab And RightCtrl
TextChanged事件:
在网上有不少关入这方面的资料,下面是我选用的一个方案
public NumberTextBox()
{
InitializeComponent();
this.KeyDown += NumberTextBox_KeyDown;
this.TextChanged += NumberTextBox_TextChanged;
}
void NumberTextBox_KeyDown(object sender, KeyEventArgs e)
{
if ((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
void NumberTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
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(this.Text, out num))
{
this.Text = this.Text.Remove(offset, change[0].AddedLength);
this.Select(offset, 0);
}
}
}
但是这个方案当输入法为中文的时候效果不理想,于是想到了禁用输入法。
引入xmlns:input="clr-namespace:System.Windows.Input;assembly=PresentationCore"
然后再 TextBox控件的xaml中 input:InputMethod.IsInputMethodEnabled="False" 就可以了。
标签:
原文地址:http://www.cnblogs.com/changbaishan/p/4241557.html