如何在 .NET/Visual Studio 中创建可浏览的类属性

Mac*_*iej 7 .net c# user-interface components visual-studio

我如何在 VS 属性窗口(可折叠的多属性)中制作这样的东西:

在此处输入图片说明

我试过这样的代码:

   Test z = new Test();

    [ Browsable(true)]
    public Test _TEST_ {
        get { return z; }
        set { z = value; }
    }
Run Code Online (Sandbox Code Playgroud)

其中“测试”类是:

[Browsable(true)] 
public class Test {
    [Browsable(true)] 
    public string A { get;set; }
    [Browsable(true)] 
    public string B { get;set; }
}
Run Code Online (Sandbox Code Playgroud)

但这只给了我灰色的班级名称

在此处输入图片说明

Max*_*lay 4

好的,我有一些工作可以满足您的需求。

要让类在 PropertyGrid 中展开,您必须TypeConverterAttribute向其中添加 a,并引用 an 的类型ExpandableObjectConverter(或从它派生的其他内容)。

[TypeConverter(typeof(ExpandableObjectConverter))]
public class Test
{
    [Browsable(true)]
    public string A { get; set; }
    [Browsable(true)]
    public string B { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

唯一的问题是它现在显示类型名称(其方法的返回值ToString()作为类的值)。您可以接受它(您可能不希望这样做),将ToString()返回值更改为更合适的值,或者TypeConverter针对这种情况使用自定义值。

我将向您展示如何快速实现后者:

internal class TestConverter : ExpandableObjectConverter
{
    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string))
            return "";
        return base.ConvertTo(context, culture, value, destinationType);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你会写这个,而不是我上面写的:

[TypeConverter(typeof(TestConverter))]
public class Test
{
    [Browsable(true)]
    public string A { get; set; }
    [Browsable(true)]
    public string B { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这只会清空信息并阻止用户输入其他值。您可能想展示一些更具描述性的内容,这完全取决于您。
还可以获取信息并将其解析为有用的值。一个很好的例子是位置,它是一个Point[10,5]when Xis10Yis可视化的类型的对象5。当您输入新值时,它们将被解析并设置为原始字符串引用的整数。


因为我找不到太多关于该主题的信息,所以我在ReferenceSource中查找了一些参考资料,因为它之前必须完成。就我而言,我查看了WindowsForms 的ButtonBaseFlatButtonAppearance,看看 Microsoft 当年是如何做到的。

希望我能帮忙。