C# 如何在 PropertyGrid 中,对同一double的成员显示出不同的长度的内容?

这段时间搞东西,接触到这个,整了好几天。终于 Stackoverflow 上找到一个与我思路上一样的答案。之前用了好多遍 百度 AI 的方法都牛头不对马嘴。

看来 自己对 这一套 C# 的中的反射机制中的内容还不是太熟悉。所以摸了好久。

主要思路是这样的:

PropertyGrid 可以把一个对象中 public 成员 都显示到界面上去,供使用者修改,如下:

这个对象的类是这样的:

1 public class testObject
2 {
3     [TypeConverter(typeof(CustomDoubleConverter)), PrecisonAttribute(3), Category("all"), Description("this is a double 1")]
4     public double MyDouble1 { get; set; }
5 
6     [TypeConverter(typeof(CustomDoubleConverter)), PrecisonAttribute(2), Category("all"), Description("this is a double 2")]
7     public double MyDouble2 { get; set; }
8 }

在主程序里是这样把这个 对象 与 PropertyGrid 关联起来的:

复制代码
public Form1()
{
   testObject to = new testObject();
InitializeComponent(); to.MyDouble1
= 1.2222f; to.MyDouble2 = 2.1f; propertyGrid1.SelectedObject = to; }
复制代码

显示出来是这样的:

可以看到,通过指定不同值的 PrecisonAttribute,让两个都是 double 的值,在 PropertyGrid 里显示出不同长度的小数点后长度值。

上面 testObject 里,两个 double 成员,都指定了 自定义的 typeConverter 的类 CustomDoubleConverter,如下:

复制代码
public class CustomDoubleConverter : DoubleConverter
{

    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string) && value is double doubleValue)
        {
            int d = 0;

            if ( context != null )
            {
                AttributeCollection ac = context.PropertyDescriptor.Attributes;

                PrecisonAttribute pa = (PrecisonAttribute)ac[typeof(PrecisonAttribute)];
                if (pa != null)
                    d = pa.Precison;
            }

            return doubleValue.ToString("N" + d, culture);
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

public class PrecisonAttribute : Attribute
{
    // The constructor is called when the attribute is set.
    public PrecisonAttribute(int value)
    {
        _precison = value;
    }

    // Keep a variable internally ...
    protected int _precison;

    // .. and show a copy to the outside world.
    public int Precison
    {
        get { return _precison; }
        set { _precison = value; }
    }
}
复制代码

以上这段代码里:

AttributeCollection ac = context.PropertyDescriptor.Attributes;

PrecisonAttribute pa = (PrecisonAttribute)ac[typeof(PrecisonAttribute)];

这两句就是本文精华。之前整了好久,都找不到如何在这里获得传入的其它元数据的。主要还是自己对 TypeConverter 结构 以及 反射机制不是很熟悉。所以也没仔细去看 context 这个参数。现在想想应该还是蛮合理的:上下文。

posted @   PencilStart  阅读(106)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
点击右上角即可分享
微信分享提示