创建十六进制NumericUpDown控件

Bor*_*ris 8 .net c# winforms

我通过对基本NumericUpDown进行子类化并添加以下方法来创建十六进制NumericUpDown控件:

protected override void UpdateEditText()
{
  this.Text = "0x" + ((int) Value).ToString("X2");
}
Run Code Online (Sandbox Code Playgroud)

这非常有效.控件现在以以下格式显示值:

0x3F的

这正是我追求的.

但有一件事困扰我:每次分配Text -property时,都会抛出System.FormatException.这似乎不会影响控件的功能,但我认为它仍然很难看.

这是callstack的顶部:

MyAssembly.dll!HexNumericUpDown.UpdateEditText()第31行C#System.Windows.Forms.dll!System.Windows.Forms.NumericUpDown.ValidateEditText()未知的System.Windows.Forms.dll!System.Windows.Forms.UpDownBase.Text. set(字符串值)未知

我可以忽略这个例外吗?或者有一个干净的方法来摆脱这个?

Han*_*ant 6

您需要覆盖ValidateEditText()方法,以便正确处理(可选)"0x"前缀.并将UpdateEditText()覆盖为前缀"0x".在项目中添加一个新类并粘贴下面显示的代码.编译.将新控件从工具箱顶部拖放到表单上:

using System;
using System.Windows.Forms;

class HexUpDown : NumericUpDown {
    public HexUpDown() {
        this.Hexadecimal = true;
    }

    protected override void ValidateEditText() {
        try {
            var txt = this.Text;
            if (!string.IsNullOrEmpty(txt)) {
                if (txt.StartsWith("0x")) txt = txt.Substring(2);
                var value = Convert.ToDecimal(Convert.ToInt32(txt, 16));
                value = Math.Max(value, this.Minimum);
                value = Math.Min(value, this.Maximum);
                this.Value = value;
            }
        }
        catch { }
        base.UserEdit = false;
        UpdateEditText();
    }

    protected override void UpdateEditText() {
        int value = Convert.ToInt32(this.Value);
        this.Text = "0x" + value.ToString("X4");
    }
}
Run Code Online (Sandbox Code Playgroud)

Fwiw,古怪的try/catch-em-all直接来自.NET版本.我保持它以使控制行为相同.以你想要的方式调整ToString()参数.