我想通过反射设置对象的对齐属性(水平/垂直),其值为字符串类型。我使用类似的东西
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 中读取属性,只有 HorizontalAlignment="Stretch"。比我创建新的 Control 实体而且我不知道如何设置属性,如 HorizontalAlignment,其中值为“Stretch”等。它会导致异常“从 'System.String' 到 'System.Windows.HorizontalAlignment' 的无效转换。 "