C# 使用字符串值通过反射设置对齐特性

C# 使用字符串值通过反射设置对齐特性,c#,wpf,reflection,alignment,setvalue,C#,Wpf,Reflection,Alignment,Setvalue,我想通过反射设置对象的align属性(水平/垂直),值类型为string。我用的是 private void SetPropertiesFromString(object nav, string properties) { Regex r = new Regex("`(?<property>[^~]*)~(?<values>[^`]*)"); MatchCollection mc = r.Matches(properties);

我想通过反射设置对象的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);  
    }  
}
private void SetPropertiesFromString(对象导航,字符串属性)
{  
正则表达式r=新正则表达式(“`(?[^~]*)~(?[^`]*)”;
MatchCollection mc=r.Matches(属性);
Type Type=nav.GetType();
对于(int i=0;i
(一模一样)


我的问题是,我从XML读取属性,只有HorizontalAlignment=“Stretch”。然后我创建了一个新的控件实体,我不知道如何设置属性,比如HorizontalAlignment,其中的值是“Stretch”等等。这会导致异常“从'System.String'转换为'System.Windows.HorizontalAlignment'无效”。

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

谢谢您的回答。但在for循环中可以是PropertyInfo prop=type.GetProperty(“Height”);属性设置值(导航,“45”,属性类型),null);在第一种情况下,但在第二种情况下,可以有PropertyInfo prop=type.GetProperty(“HorizontalAlignment”);属性设置值(导航,“拉伸”,属性类型),null);那么我就不能很容易地将它转换为枚举值。顺便说一句,margin也存在同样的问题。然后,您需要检查目标属性的类型,如果它是enum,请在设置它之前尝试解析它,我想不出其他更简单的方法。