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("`(?<property>[^~]*)~(?<values>[^`]*)");
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 H开发者_运维技巧orizontalAlignment="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'."
HorizontalAlignment is an enum type. System.Enum.Parse lets you convert a string to the corresponding enum value.
精彩评论