gpt4 book ai didi

c# - PropertyGrid 和对象的动态类型

转载 作者:太空狗 更新时间:2023-10-29 23:19:23 27 4
gpt4 key购买 nike

我正在编写一个 GUI 应用程序,我需要在其中启用任意对象的编辑属性(它们的类型仅在运行时已知)。

我决定使用 PropertyGrid 控件来启用此功能。我创建了以下类:

[TypeConverter(typeof(ExpandableObjectConverter))]
[DefaultPropertyAttribute("Value")]
public class Wrapper
{
public Wrapper(object val)
{
m_Value = val;
}

private object m_Value;

[NotifyParentPropertyAttribute(true)]
[TypeConverter(typeof(ExpandableObjectConverter))]
public object Value
{
get { return m_Value; }
set { m_Value = value; }
}
}

当我得到一个我需要编辑的对象的实例时,我为它创建一个 Wrapper 并将它设置为选定的对象:

Wrapper wrap = new Wrapper(obj);
propertyGrid.SelectedObject = wrap;

但我遇到了以下问题 - 只有当 obj 的类型是某种自定义类型(即我自己定义的类,或内置的复杂类型)时,以上才会按预期工作,但当 obj 是一个原始的。

例如,如果我定义:

[TypeConverter(typeof(ExpandableObjectConverter))]
public class SomeClass
{
public SomeClass()
{
a = 1;
b = 2;
}

public SomeClass(int a, int b)
{
this.a = a;
this.b = b;
}

private int a;

[NotifyParentPropertyAttribute(true)]
public int A
{
get { return a; }
set { a = value; }
}

private int b;

[NotifyParentPropertyAttribute(true)]
public int B
{
get { return b; }
set { b = value; }
}
}

然后做:

Wrapper wrap = new Wrapper(new SomeClass());
propertyGrid.SelectedObject = wrap;

然后一切正常。另一方面,当我执行以下操作时:

int num = 1;
Wrapper wrap = new Wrapper(num);
propertyGrid.SelectedObject = wrap;

然后我可以在网格中看到值“1”(并且它不是灰度的)但我无法编辑该值。我注意到,如果我将 Wrapper 的“Value”属性的类型更改为 int 并删除 TypeConverter 属性,它就会起作用。对于其他原始类型和字符串,我得到了相同的行为。

问题是什么?

提前致谢!

最佳答案

如果您将 ExpandableObjectConverter 设置为您的 Value 属性,它将不可编辑,这是正常的,因为 CanConvertFrom 将返回 false。如果您删除类型转换器,PropertyGrid 将使用通用的 TypeConverter,您将再次遇到相同的情况。因此,解决方法是附加一个更智能的 TypeConverter,它将充当正确 TypeConverter 的包装器。这是一个脏的(我没有太多时间,你将根据需要完成它,因为我刚刚实现了 ConvertFrom 部分):

public class MySmartExpandableObjectConverter : ExpandableObjectConverter
{
TypeConverter actualConverter = null;

private void InitConverter(ITypeDescriptorContext context)
{
if (actualConverter == null)
{
TypeConverter parentConverter = TypeDescriptor.GetConverter(context.Instance);
PropertyDescriptorCollection coll = parentConverter.GetProperties(context.Instance);
PropertyDescriptor pd = coll[context.PropertyDescriptor.Name];

if (pd.PropertyType == typeof(object))
actualConverter = TypeDescriptor.GetConverter(pd.GetValue(context.Instance));
else
actualConverter = this;
}
}

public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
InitConverter(context);

return actualConverter.CanConvertFrom(context, sourceType);
}

public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
InitConverter(context); // I guess it is not needed here

return actualConverter.ConvertFrom(context, culture, value);
}
}

如果您需要微调某些东西,请告诉我。

尼古拉斯

关于c# - PropertyGrid 和对象的动态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1884851/

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