c# - 如何使用 WinForms PropertyGrid 编辑字符串列表?

标签 c# string winforms propertygrid

在我的应用程序中,我有一个允许用户更改设置的属性网格。这适用于字符串和其他值属性,但我现在需要的是用户可以编辑的字符串列表。

问题是如果我有MyPropertyGrid.SelectedObject = new { Test = new List<string>() };在我的代码中,用户尝试编辑 Test属性,当他们单击“添加”按钮时,会发生以下错误:

 Constructor on type 'System.String' not found

这是有道理的,因为字符串是不可变的。但是,我仍然需要一些方法来在属性网格中存储多个字符串(或类似字符串的数据)。

有没有人对我如何实现这一目标有任何想法?

最佳答案

是的,你可以specify an System.ComponentModel.Editor attribute on your list of strings, with StringCollectionEditor as the editor .您需要将对 System.Design.Dll 的引用添加到您的项目中,以便进行编译。

例如,假设您的对象是这样的:

[DefaultProperty("Name")]
public class CustomObject
{
    [Description("Name of the thing")]
    public String Name { get; set; }

    [Description("Whether activated or not")]
    public bool Activated { get; set; }

    [Description("Rank of the thing")]
    public int Rank { get; set; }

    [Description("whether to persist the settings...")]
    public bool Ephemeral { get; set; }

    [Description("extra free-form attributes on this thing.")]
    [Editor(@"System.Windows.Forms.Design.StringCollectionEditor," +
        "System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
       typeof(System.Drawing.Design.UITypeEditor))]
    [TypeConverter(typeof(CsvConverter))]
    public List<String> ExtraStuff
    {
        get
        {
            if (_attributes == null)
                _attributes = new List<String>();
            return _attributes;
        }
    }
    private List<String> _attributes;
}

它的属性网格如下所示:

enter image description here

点击 ...你会得到:

enter image description here

如果您不喜欢内置的收藏编辑器,you can implement your own custom collection editor .

我的示例展示了 TypeConverter 属性的使用。如果您不这样做,则列表在 Prop 网格中显示为“(收藏)”。类型转换器 gets it to display as something intelligent .例如,要在属性网格中显示集合的短字符串表示形式,如下所示:

enter image description here

...TypeConverter 是这样的:

public class CsvConverter : TypeConverter
{
    // Overrides the ConvertTo method of TypeConverter.
    public override object ConvertTo(ITypeDescriptorContext context,
       CultureInfo culture, object value, Type destinationType)
    {
        List<String> v = value as List<String>;
        if (destinationType == typeof(string))
        {
            return String.Join(",", v.ToArray()); 
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

您不需要 List<String> 上的二传手,因为集合编辑器不设置该属性,它只是向属性添加或删除条目。所以只需提供 setter/getter 即可。

关于c# - 如何使用 WinForms PropertyGrid 编辑字符串列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6307006/

相关文章:

c# - .NET核心JWE : no "cty" header

c# - 两个程序集名称相同、版本相同但公钥不同

java - 使用带有继承的 Jackson 将字符串映射到对象

java - 堆内存和字符串池的区别

winforms - 如何检测工作站锁

c# - C# 中的流右移运算符等效吗?

c# - 有什么方法可以使 XmlSerializer 以定义的顺序输出 xml?

c++ - 如何将字符串分配给 MessageBox C++?

c# - 如何将剪贴板中的文本粘贴到文本框中的光标区域

c# - 如何从工具提示中查找控件