WPF 数字文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12256092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF numeric textbox
提问by Alvin
How can I have a WPF numberic textbox with two decimal point, for example:
我怎样才能有一个带两个小数点的 WPF 数字文本框,例如:
It will start with 0.00, when user key in 1, the value will be 0.01, next when user user key in 2, the value will be 0.21.
从0.00开始,当用户输入1时,值为0.01,接下来当用户输入2时,值为0.21。
When user key in 5003, the value is 30.05.
当用户键入 5003 时,该值为 30.05。
Thnak you.
想你。
回答by Erre Efe
Sure you can always implemented one as @JesseJames already suggested. But, I'll suggest you to better use an existing one, I believe the Extended WPF Toolkitis what you need, precisely the IntegerUpDown(you can specify the mask you need, it comes with 5):
当然,您始终可以按照@JesseJames 已经建议的方式实施。但是,我建议您更好地使用现有的,我相信Extended WPF Toolkit正是您所需要的,正是 IntegerUpDown(您可以指定所需的掩码,它带有 5 个):
<xctk:IntegerUpDown FormatString="N0" Value="1" Increment="1" Maximum="100"/>
回答by opewix
You can implement it in KeyDown event handler. Set event argument property e.Handle = trueand calculate output number.
您可以在 KeyDown 事件处理程序中实现它。设置事件参数属性e.Handle = true并计算输出数。
Don't write like me, it's just example :))
不要像我一样写,这只是例子:))
public partial class MainWindow : Window
{
private StringBuilder sb = new StringBuilder();
public MainWindow()
{
InitializeComponent();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
e.Handled = true;
switch (e.Key)
{
case Key.D0: { if (sb.Length == 2) sb.Insert(0, ','); sb.Insert(0, 0); break; }
case Key.D1: { if (sb.Length == 2) sb.Insert(0, ','); sb.Insert(0, 1); break; }
case Key.D2: { if (sb.Length == 2) sb.Insert(0, ','); sb.Insert(0, 2); break; }
case Key.D3: { if (sb.Length == 2) sb.Insert(0, ','); sb.Insert(0, 3); break; }
case Key.D4: { if (sb.Length == 2) sb.Insert(0, ','); sb.Insert(0, 4); break; }
case Key.D5: { if (sb.Length == 2) sb.Insert(0, ','); sb.Insert(0, 5); break; }
case Key.D6: { if (sb.Length == 2) sb.Insert(0, ','); sb.Insert(0, 6); break; }
case Key.D7: { if (sb.Length == 2) sb.Insert(0, ','); sb.Insert(0, 7); break; }
case Key.D8: { if (sb.Length == 2) sb.Insert(0, ','); sb.Insert(0, 8); break; }
case Key.D9: { if (sb.Length == 2) sb.Insert(0, ','); sb.Insert(0, 9); break; }
}
textBox1.Text = sb.ToString();
}
}
In this example you also need to handle "Backspace" hit to clear StringBuilder. To get the value, use parser: double result = double.Parse(sb.ToString());+ Handle NumPad numbers!
在此示例中,您还需要处理“Backspace”命中以清除 StringBuilder。要获取值,请使用解析器:double result = double.Parse(sb.ToString());+ 处理数字键盘数字!

