在WinForms中,能否在NumericUpDown控件内显示文本?例如,我想在我的numericupdown控件中显示值为微安的文本,应该是"1 uA"。
谢谢。
在WinForms中,能否在NumericUpDown控件内显示文本?例如,我想在我的numericupdown控件中显示值为微安的文本,应该是"1 uA"。
谢谢。
标准控件中没有这样的功能。但是,可以通过创建一个继承自 NumericUpDown
类并重写 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
ValidateEditText()
的默认实现如果文本中有后缀则会失败。您还必须覆盖ValidateEditText()
以将文本转换为数字值。 - Fabio使用CodeGray的答案,Fabio对其无法通过ValidateEditText的评论以及NumericUpDown文档,我创建了一个简单的带单位的NumericUpDown组件。您可以直接复制粘贴如下:
using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Forms;
public class NumericUpDownWithUnit : NumericUpDown
{
#region| Fields |
private string unit = null;
private bool unitFirst = true;
#endregion
#region| Properties |
public string Unit
{
get => unit;
set
{
unit = value;
UpdateEditText();
}
}
public bool UnitFirst
{
get => unitFirst;
set
{
unitFirst = value;
UpdateEditText();
}
}
#endregion
#region| Methods |
/// <summary>
/// Method called when updating the numeric updown text.
/// </summary>
protected override void UpdateEditText()
{
// If there is a unit we handle it ourselfs, if there is not we leave it to the base class.
if (Unit != null && Unit != string.Empty)
{
if (UnitFirst)
{
Text = $"({Unit}) {Value}";
}
else
{
Text = $"{Value} ({Unit})";
}
}
else
{
base.UpdateEditText();
}
}
/// <summary>
/// Validate method called before actually updating the text.
/// This is exactly the same as the base class but it will use the new ParseEditText from this class instead.
/// </summary>
protected override void ValidateEditText()
{
// See if the edit text parses to a valid decimal considering the label unit
ParseEditText();
UpdateEditText();
}
/// <summary>
/// Converts the text displayed in the up-down control to a numeric value and evaluates it.
/// </summary>
protected new void ParseEditText()
{
try
{
// The only difference of this methods to the base one is that text is replaced directly
// with the property Text instead of using the regex.
// We now that the only characters that may be on the textbox are from the unit we provide.
// because the NumericUpDown handles invalid input from user for us.
// This is where the magic happens. This regex will match all characters from the unit
// (so your unit cannot have numbers). You can change this regex to fill your needs
var regex = new Regex($@"[^(?!{Unit} )]+");
var match = regex.Match(Text);
if (match.Success)
{
var text = match.Value;
// VSWhidbey 173332: Verify that the user is not starting the string with a "-"
// before attempting to set the Value property since a "-" is a valid character with
// which to start a string representing a negative number.
if (!string.IsNullOrEmpty(text) && !(text.Length == 1 && text == "-"))
{
if (Hexadecimal)
{
Value = Constrain(Convert.ToDecimal(Convert.ToInt32(Text, 16)));
}
else
{
Value = Constrain(Decimal.Parse(text, CultureInfo.CurrentCulture));
}
}
}
}
catch
{
// Leave value as it is
}
finally
{
UserEdit = false;
}
}
/// </summary>
/// Returns the provided value constrained to be within the min and max.
/// This is exactly the same as the one in base class (which is private so we can't directly use it).
/// </summary>
private decimal Constrain(decimal value)
{
if (value < Minimum)
{
value = Minimum;
}
if (value > Maximum)
{
value = Maximum;
}
return value;
}
#endregion
}
ChangingText
来避免使用“去抖动”。 class HexNumericUpDown2Digits : NumericUpDown
{
protected override void UpdateEditText()
{
if (Hexadecimal)
{
ChangingText = true;
Text = $"0x{(int)Value:X2}";
}
else
{
base.UpdateEditText();
}
}
}
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;
}
}
当您的对象发生更改后,您的操作将开始,您需要在属性部分双击“ValueChanged”。 此操作完成后,您可以在代码中看到以下代码:
private void numericUpDownMounth_ValueChanged(object sender, EventArgs e)
{
// Body
}
在//Body侧,您可以编写您的代码和控制器。就像其他人说的那样。