1

我想通过反射设置对象的对齐属性(水平/垂直),其值为字符串类型。我使用类似的东西

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"。比我创建新的 Control 实体而且我不知道如何设置属性,如 Horizo​​ntalAlignment,其中值为“Stretch”等。它会导致异常“从 'System.String' 到 'System.Windows.Horizo​​ntalAlignment' 的无效转换。 "

4

1 回答 1

0

Horizo​​ntalAlignment 是一个枚举类型。System.Enum.Parse 允许您将字符串转换为相应的枚举值。

于 2010-09-14T08:10:56.523 回答