【问题标题】:Setting alignment property by reflection with a string value使用字符串值通过反射设置对齐属性
【发布时间】:2011-04-12 01:04:46
【问题描述】:

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

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

(很像this

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

【问题讨论】:

    标签: c# wpf reflection alignment setvalue


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答。但在 for 循环中可能是 PropertyInfo prop = type.GetProperty("Height"); prop.SetValue(nav, "45", prop.PropertyType), null);在第一种情况下,但在第二种情况下可以有 PropertyInfo prop = type.GetProperty("Horizo​​ntalAlignment"); prop.SetValue(nav, "Stretch", prop.PropertyType), null);然后我不能轻易地将它转换为枚举值。顺便说一句 - 保证金也有同样的问题。
    • 那你需要检查目标属性的类型,如果是枚举的话在设置之前尝试解析一下,没有其他更简单的办法了。
    猜你喜欢
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 2020-05-18
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多