如何让wpf 中的textbox只能输入整型或浮点型呢??
展开全部
没必要,WPF最好使用Validator进行验证,或者也可以在确认的时候检查一下即可。
如果执意要这样做,也给你段代码:
private void TextBoxNumbersOnly(object sender, TextChangedEventArgs e)
{
var box = (TextBox)sender;
var start = box.SelectionStart;
for (var i = 0; i < box.Text.Length; i++) if (!char.IsNumber(box.Text[i]))
{
if (i < start) start--;
box.Text = box.Text.Remove(i, 1);
i--;
}
box.Select(start, 0);
}
如果执意要这样做,也给你段代码:
private void TextBoxNumbersOnly(object sender, TextChangedEventArgs e)
{
var box = (TextBox)sender;
var start = box.SelectionStart;
for (var i = 0; i < box.Text.Length; i++) if (!char.IsNumber(box.Text[i]))
{
if (i < start) start--;
box.Text = box.Text.Remove(i, 1);
i--;
}
box.Select(start, 0);
}
展开全部
privatevoid tbCount_KeyDown(object sender, KeyEventArgs e)
{
TextBox txt = sender as TextBox;
//屏蔽非法按键
if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal || e.Key.ToString() =="Tab")
{
if (txt.Text.Contains(".") && e.Key == Key.Decimal)
{
e.Handled =true;
return;
}
e.Handled =false;
}
elseif (((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)
{
e.Handled =true;
return;
}
e.Handled =false;
}
else
{
e.Handled =true;
}
}
privatevoid 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);
}
}
}
{
TextBox txt = sender as TextBox;
//屏蔽非法按键
if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal || e.Key.ToString() =="Tab")
{
if (txt.Text.Contains(".") && e.Key == Key.Decimal)
{
e.Handled =true;
return;
}
e.Handled =false;
}
elseif (((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)
{
e.Handled =true;
return;
}
e.Handled =false;
}
else
{
e.Handled =true;
}
}
privatevoid 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);
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询