在数字后面有NumericUpDown控件内的文本

在WinForms中是否可以在NumericUpDown控件中显示文本? 例如,我想在我的numericupdown控件中显示值是微安培,所以它应该像“1 uA”。

谢谢。

标准控件中没有内置的function。 但是,通过创建从NumericUpDown类inheritance的自定义控件并覆盖UpdateEditText方法以相应地格式化数字,可以相当容易地添加它。

例如,您可能具有以下类定义:

 public class NumericUpDownEx : NumericUpDown { public NumericUpDownEx() { } protected override void UpdateEditText() { // Append the units to the end of the numeric value this.Text = this.Value + " uA"; } } 

或者,要获得更完整的实现,请参阅此示例项目: 带有单位度量的NumericUpDown

我最近偶然发现了这个问题,并找到了Cody Gray的精彩答案。 我使用它对我有利,但最近引起了他的答案之一的评论,他们谈到如果后缀仍然存在,文本将如何validation失败。 我为此创建了一个可能不那么专业的快速修复程序。

基本上, this.Text字段是为数字读取的。

一旦找到数字,就会将它们放入this.Text ,但需要进行去抖或任何你想要调用的数据,以确保我们不会创建堆栈溢出

一旦只有数字的新文本在,正常的ParseEditText();UpdateEditText(); 被称为完成该过程。

这不是最资源友好或最有效的解决方案,但今天大多数现代计算机应该完全没问题。

另外你会注意到我创建了一个用于更改后缀的属性,以便在编辑器中更容易使用。

 public class NumericUpDownUnit : System.Windows.Forms.NumericUpDown { public string Suffix{ get; set; } private bool Debounce = false; public NumericUpDownUnit() { } protected override void ValidateEditText() { if (!Debounce) //I had to use a debouncer because any time you update the 'this.Text' field it calls this method. { Debounce = true; //Make sure we don't create a stack overflow. string tempText = this.Text; //Get the text that was put into the box. string numbers = ""; //For holding the numbers we find. foreach (char item in tempText) //Implement whatever check wizardry you like here using 'tempText' string. { if (Char.IsDigit(item)) { numbers += item; } else { break; } } decimal actualNum = Decimal.Parse(numbers, System.Globalization.NumberStyles.AllowLeadingSign); if (actualNum > this.Maximum) //Make sure our number is within min/max this.Value = this.Maximum; else if (actualNum < this.Minimum) this.Value = this.Minimum; else this.Value = actualNum; ParseEditText(); //Carry on with the normal checks. UpdateEditText(); Debounce = false; } } protected override void UpdateEditText() { // Append the units to the end of the numeric value this.Text = this.Value + Suffix; } } 

如果出现问题,请随时更好地回答或纠正我,我是一名自学成才的程序员,仍然在学习。