前一段时间在使用NumericUpDown的时候,发现了一个在设置Hexcadecimal为True时候的bug:
即使设置Maximum为4294967295(0xFFFFFFFF),但是控件也不接受大于2147483647(0x7FFFFFFF)的数。
后来在http://social.msdn.microsoft.com/forums/en-US/winforms/thread/6eea9c6c-a43c-4ef1-a7a3-de95e17e77a8/上查询得知NumericUpDown使用Convert.ToInt32()来转换输入的文本,因此大于0x7FFFFFFF的数值将得到负数,导致控件不接受输入的值。
解决的方式是从NumericUpDown继承写一个HexNumericUpDown控件来解决问题,代码如下:
using System;
using System.ComponentModel;
using System.Windows.Forms;
public class HexNumericUpDown : NumericUpDown
{
[Browsable(false)]
public new bool Hexadecimal
{
get
{
return base.Hexadecimal;
}
set
{
base.Hexadecimal = value;
}
}
public HexNumericUpDown()
{
base.Hexadecimal = false;
base.Minimum = 0;
base.Maximum = UInt32.MaxValue;
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new decimal Maximum
{
// Doesn't serialize properly
get { return base.Maximum; }
set { base.Maximum = value; }
}
protected override void UpdateEditText()
{
if (base.UserEdit == true)
{
HexParseEditText();
}
if (string.IsNullOrEmpty(base.Text) == false)
{
base.ChangingText = true;
base.Text = string.Format("{0:X}", (uint)base.Value);
}
}
protected override void ValidateEditText()
{
HexParseEditText();
UpdateEditText();
}
private void HexParseEditText()
{
try
{
if (string.IsNullOrEmpty(base.Text) == false)
{
this.Value = Convert.ToInt64(base.Text, 16);
}
}
catch
{
}
finally
{
base.UserEdit = false;
}
}
}
作者:Harry Huang
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利.
浙公网安备 33010602011771号