views:

65

answers:

1

Hi,
I'd like to set align property (horizontal/vertical) of an object through reflection, with a value of type string. I use something like

private void SetPropertiesFromString(object nav, string properties)
{
Regex r = new Regex("
(?[^~]*)~(?[^]*)");
MatchCollection mc = r.Matches(properties);
Type type = nav.GetType();
for (int i = 0; i < mc.Count; i++)
{
PropertyInfo prop = type.GetProperty(mc[i].Groups["property"].Value);
prop.SetValue(nav, Convert.ChangeType(mc[i].Groups["values"].Value, prop.PropertyType), null);
}
}

(Quite same like this)

My problem is, that I'm reading properties from XML, there is only HorizontalAlignment="Stretch". Than I create new entity of Control and I don't know, how to set property like HorizontalAlignment, where value is "Stretch" etc. It causes exception "Invalid cast from 'System.String' to 'System.Windows.HorizontalAlignment'."

A: 

HorizontalAlignment is an enum type. System.Enum.Parse lets you convert a string to the corresponding enum value.

Mattias S
Thanks for answer. But in for cycle could be PropertyInfo prop = type.GetProperty("Height");prop.SetValue(nav, "45", prop.PropertyType), null); in the first case, but in second case there can be PropertyInfo prop = type.GetProperty("HorizontalAlignment");prop.SetValue(nav, "Stretch", prop.PropertyType), null); Then I can't convert it easily to enum value. By the way - same problem is with margin.
Kosti
Then you need to inspect the type of the target property, and if it's enum try to parse it before setting it, there's no other easier way I can think of.
Alex Paven
Omg... thanks for your idea, nice work :)
Kosti