PropertyInfo.SetValue on new ObjectCollect

G

Guest

I have a Windows Forms designer that writes the created form (with controls)
as Xml/Xaml. Alternately it reads Xml/Xaml to create form controls in the
designer form. I am trying to do this using reflection. I can use
Activator.CreateInstance to create the controls and can set most of the
properties using just a little bit of code:

info.SetValue(temp,
TypeDescriptor.GetConverter(info.PropertyType).ConvertFrom(val), null);
where info is the PropertyInfo for the control property that will be set,
temp is the control, and val is the string representation of the value.

This breaks for some properties like font and the Items collection for some
controls. It is the latter that I am looking for help with.

The problem is that when I create the new control using CreateInstance the
control is returned with an empty Items collection. To further complicate the
matter, the instance is returned as an object. I could simply determine the
control type and use a switch statement to add each Item to the collection.
That can lead to alot of code and a lot of maintenance. My goal is to
populate the Items collection generically using reflection as I am already
doing for most of the properties.

I can use CreateInstance to create an value object but since the control is
cast as an object, it does not reveal the Items collection and I can
therefore not add the new value object.

Does anyone know how to populate the Items collection of a control using
reflection?
 
G

Guest

Well I figured out the answer myself. It was far simpler than I was making it
out. The solution is 3 lines of code:

object obj = info.GetValue(temp, null);
MethodInfo add = info.PropertyType.GetMethod("Add");
add.Invoke(obj, new object[] { val });

I just needed to get the Add method and invoke it.

So now I am working on the second part mentioned below: Font. Not quite so
simple there. I have looked at the available Font Constructors and it looks
like I can set the font by creating a new font using one of the constructors.
It will be a pain to manually write the Font property value with each of the
subproperty values in the correct sequence. It will be even worse taking the
comma delimited string and parsing each member to the correct type to be
rebuilt.

Does anyone know an easier way?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top