As we know that by default the winform PropertyGrid is able to edit properties of a predefined class. However, some times we might need to edit dynamic created objects. Refer to the code below:
ParamForm.Show(new { Firstname = "John", Lastname = "Herby" })
The ParamForm window contains 2 controls, a PropertyGrid and a Button. It is designed to be able to edit dynamic objects which contains string or boolean fields only.
public static dynamic Show(dynamic args)
{
var frm = new ParamForm(args);
frm.ShowDialog();
return frm.Result;
}
public ParamForm(dynamic args)
{
InitializeComponent();
propertyGrid.SelectedObject = ag;
}
The problem is that the Firstname & Lastname displayed in PropertyGrid control is grayed out and cannot be edited. So how to make the PropertyGrid able to edit dynamic created objects?
Anonymous types have read only property descriptors (used by the property grid) by design (see here for more on this: Non-read only alternative to anonymous types).
You can however use tricks such as the DynamicTypeDescriptorWrapper
class demonstrated here: Fun with C# 4.0’s dynamic that implement the ICustomTypeDescriptor Interface