选项对话框/选项属性网格

本文关键字:选项 网格 属性 对话框 | 更新日期: 2023-09-27 18:21:49

您知道如何设置属性(如果存在)以十六进制格式显示对象中的所有数值吗。我使用这个代码:

  OptionsDialog options = new OptionsDialog();
  options.OptionsPropertyGrid.SelectedObject = myobject //<--this object contains numeric value

现在在我的对象编辑器上,我可以修改值,但以十进制格式显示。

选项对话框/选项属性网格

使用转换器:

public class IntToHexTypeConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        if (sourceType == typeof(string))
        {
            return true;
        }
        else
        {
            return base.CanConvertFrom(context, sourceType);
        }
    }
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        if (destinationType == typeof(string))
        {
            return true;
        }
        else
        {
            return base.CanConvertTo(context, destinationType);
        }
    }
    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string) && value.GetType() == typeof(int))
        {
            return string.Format("0x{0:X8}", value);
        }
        else
        {
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        if (value.GetType() == typeof(string))
        {
            string input = (string)value;
            if (input.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            {
                input = input.Substring(2);
            }
            return int.Parse(input, NumberStyles.HexNumber, culture);
        }
        else
        {
            return base.ConvertFrom(context, culture, value);
        }
    }
}

为要与PropertyGrid关联的数据定义一个类:

[DefaultPropertyAttribute("Name")]
public class Data 
public UInt32 stat;
[CategoryAttribute("Main Scanner"), DescriptionAttribute("Status"), TypeConverter(typeof(IntToHexTypeConverter ))]
public UInt32 Status
{
    get { return stat; }
}

propertyGrid的参考数据。(此处,myData是一个Data)。

propertyGrid1.SelectedObject = myData;

来源:http://koniosis.blogspot.nl/2009/02/integers-as-hex-in-propertygrid-c-net.html

如果使用字符串。Format(),可以指定数值的显示方式。

int i = 42;
string s = string.Format("Display as integer: {0}, or as hex: 0x{0:X}", i);
Console.Out.WriteLine(s);