繁体   English   中英

通过反射使用字符串值设置对齐方式属性

[英]Setting alignment property by reflection with a string value

我想通过反射将对象的align属性(水平/垂直)设置为string类型的值。 我用类似的东西

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);  
    }  
}

(像这样

我的问题是,我正在从XML读取属性,只有Horizo​​ntalAlignment =“ Stretch”。 比我创建控件的新实体,我不知道如何设置诸如Horizo​​ntalAlignment之类的属性,其中值是“ Stretch”等。它会导致异常“从'System.String'到'System.Windows.Horizo​​ntalAlignment'的无效转换。 ”

Horizo​​ntalAlignment是枚举类型。 System.Enum.Parse使您可以将字符串转换为相应的枚举值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM