开发者

Setting alignment property by reflection with a string value

开发者 https://www.devze.com 2023-01-15 21:09 出处:网络
I\'d like to set align property (horizontal/vertical) of an object through reflection, with a value of type string. I use something like

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号