gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:29:46 24 4
gpt4 key购买 nike

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

enter image description here

我试过这样的代码:

   Test z = new Test();

[ Browsable(true)]
public Test _TEST_ {
get { return z; }
set { z = value; }
}

其中“测试”类是:
[Browsable(true)] 
public class Test {
[Browsable(true)]
public string A { get;set; }
[Browsable(true)]
public string B { get;set; }
}

但这只给了我灰色的类(class)名称

enter image description here

最佳答案

好的,我有一些工作可以满足您的情况。

要在 PropertyGrid 中扩展一个类,您必须添加 TypeConverterAttribute到它,引用 ExpandableObjectConverter 的类型(或从它派生的其他东西)。

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

唯一的问题是它现在显示类型名称(它的 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);
}
}

然后你会写这个,而不是我上面写的:
[TypeConverter(typeof(TestConverter))]
public class Test
{
[Browsable(true)]
public string A { get; set; }
[Browsable(true)]
public string B { get; set; }
}

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

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

希望我能帮上忙。

关于c# - 如何在 .NET/Visual Studio 中创建可浏览的类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60496208/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com