1

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 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'."

Community
  • 1
  • 1
Kosti
  • 13
  • 4

1 Answers1

0

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

Mattias S
  • 4,748
  • 2
  • 17
  • 18
  • 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 Sep 14 '10 at 08:54
  • 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 Sep 14 '10 at 19:02