gpt4 book ai didi

c# - 具有多个嵌套类的 Propertygrid

转载 作者:行者123 更新时间:2023-11-30 18:27:12 41 4
gpt4 key购买 nike

我一直在研究 PropertyGrids,将它们链接到类,并试图弄清楚如何(如果可能)我可以显示一个类,在 扁平结构(好像它们都在一个类中)

我有几个类,Foo 和 Bar,如下所示:

[Serializable()]
public class Foo
{
private string m_Code;
private Bar m_Bar = new Bar();

[DisplayName("Code")]
[Description("The Code of Foo")]
public string Code
{
get { return m_Code; }
set { m_Code = value; }
}

public Bar Bar
{
get { return m_Bar; }
set { m_Bar = value; }
}
}

[TypeConverter(typeof(ExpandableObjectConverter))]
[Serializable()]
public class Bar
{
private string m_Name;

[DisplayName("Name")]
[Description("The Name of Bar")]
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}
}

我想了解/弄清楚的是,我是否可以修改数据随后在 PropertyGrid 中的显示方式。

具体来说,我想在平面/有组织的结构中同时显示 Foo.Code 和 Bar.Name,就好像它们都在同一个类中一样。

如果我不使用 TypeConverter,或尝试使用 [TypeConverter(typeof(Bar))],那么我会在 PropertyGrid 中看到我的 Bar 类,但只有一行,并且无法编辑 Name 属性.

如果我像上面那样使用 [TypeConverter(typeof(ExpandableObjectConverter))],那么我可以看到 Bar 的展开箭头,以及在其下方的 Name 属性……一切看起来都不错。

但是,我都必须展开该组,它会在右侧显示类名。显然我可以调用 PropertyGrid.ExpandAllGridItems();根据需要,但它也很丑。

如果我使用[Category("Bar")],那么它被包括在内,并根据需要组织在平面结构中,但仍然存在上述问题(展开级别和类名)

我在这里遗漏了什么明显的东西吗?还是我需要实现某种自定义类型转换器?如果是这样,该怎么做?

编辑:

为了进一步说明,当我使用嵌套类时,它显示如下,因此在右侧显示类名,并展开箭头。

enter image description here

我希望嵌套类如下所示/好像 Foo 只是一个具有代码和名称的类。

enter image description here

编辑2:

尝试实现类型转换器,似乎显示正常,但现在我根本无法编辑值(即 Bar.Name )

[TypeConverter(typeof(BarConverter))]
[Serializable()]
public class Bar
{
private string m_Name;

[DisplayName("Name")]
[Description("The Name of Bar")]
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}
}

public class BarConverter : TypeConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
Bar _Bar = (Bar)value;
return _Bar.Name;
}

}

编辑 3:

类型转换器似乎可以获取值,但现在无法编辑 Bar.Name 值,它只是变灰了:

enter image description here

当前类型转换器

public class BarConverter : TypeConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
Bar _Bar = (Bar)value;
return _Bar.Name;
}

public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
return base.ConvertFrom(context, culture, value);
}
}

编辑 #4

我认为这太难了。太多时间在兜圈子:(

最佳答案

我认为您应该覆盖 ExpandableObjectConverter 而不是 TypeConverter

public class BarConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
Bar _Bar = (Bar) value;
return _Bar.Name;
}
}

关于c# - 具有多个嵌套类的 Propertygrid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27088298/

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