You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改PropertyGrid中数组项的显示名称与帮助文本

自定义PropertyGrid数组项的显示名称与帮助文本

你现在的代码已经成功把Test数组绑定到PropertyGrid了,要把默认的(0)(1)改成自定义名称,同时添加帮助文本,其实可以通过重写ToString()+自定义类型转换器的组合来实现,步骤很清晰:

第一步:给Test类添加索引标识并重写ToString()

首先给Test类加一个ItemIndex属性用来标记每个项的序号,然后重写ToString()方法,这样PropertyGrid里的数组项就会显示我们自定义的名称:

[TypeConverter(typeof(TestConverter))] // 先加上这个,后面要用到自定义转换器
public class Test : UserControl
{
    // 新增索引属性,记录当前项的序号
    public int ItemIndex { get; set; }

    [Category("lc_Test"), Description("Testing using List<>, for storage."), DisplayName("Images")]
    public Image img { get; set; }

    // 重写ToString,替换默认的索引显示
    public override string ToString()
    {
        return $"Test Item {ItemIndex}";
    }
}

第二步:添加Test实例时赋值索引

在button7_Click方法里,给每个新增的Test对象设置ItemIndex,确保序号正确:

private void button7_Click(object sender, EventArgs e)
{
    lc_Test.Clear();
    
    // 第一个测试项
    var testItem0 = new Test();
    testItem0.ItemIndex = 0;
    testItem0.img = pb1.Image;
    lc_Test.Add(testItem0);
    
    // 第二个测试项
    var testItem1 = new Test();
    testItem1.ItemIndex = 1;
    testItem1.img = pb2.Image;
    lc_Test.Add(testItem1);

    MessageBox.Show(lc_Test.Count.ToString());
    pgTest.SelectedObject = lc_Test.ToArray();
}

第三步:自定义TypeConverter实现帮助文本

如果要给每个数组项添加专属的帮助文本(就是选中项时PropertyGrid底部显示的描述),我们需要写一个自定义的类型转换器:

public class TestConverter : ExpandableObjectConverter
{
    // 重写GetDescription方法,返回自定义帮助文本
    public override string GetDescription(ITypeDescriptorContext context, object value)
    {
        if (value is Test testItem)
        {
            // 这里可以根据索引生成不同的帮助文本,也可以写固定内容
            return $"这是第{testItem.ItemIndex + 1}个测试项,用于管理图片属性";
        }
        return base.GetDescription(context, value);
    }
}

这样做完之后,你再运行程序点击按钮,PropertyGrid里的数组项就会显示成“Test Item 0”“Test Item 1”,选中任意一项时,底部还会显示对应的帮助文本啦。

内容的提问来源于stack exchange,提问作者tobeypeters

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:34:10