众所周知,默认情况下 winform PropertyGrid 能够编辑预定义类的属性。然而,有时我们可能需要编辑动态创建的对象。引用下面的代码:
ParamForm.Show(new { Firstname = "John", Lastname = "Herby" })
ParamForm 窗口包含 2 个控件:PropertyGrid 和 Button。它被设计为能够编辑仅包含字符串或 bool 字段的动态对象。
public static dynamic Show(dynamic args)
{
var frm = new ParamForm(args);
frm.ShowDialog();
return frm.Result;
}
public ParamForm(dynamic args)
{
InitializeComponent();
propertyGrid.SelectedObject = ag;
}
问题是 PropertyGrid 控件中显示的名字和姓氏呈灰色且无法编辑。那么如何让PropertyGrid能够编辑动态创建的对象呢?
最佳答案
匿名类型在设计上只读属性描述符(由属性网格使用)(有关更多信息,请参见此处:Non-read only alternative to anonymous types)。
但是,您可以使用此处演示的 DynamicTypeDescriptorWrapper
类等技巧:Fun with C# 4.0’s dynamic实现 ICustomTypeDescriptor Interface
关于winforms - winform PropertyGrid可以编辑动态对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31446787/