有人知道如何使用反射设置第二级属性吗? 如果我想设置一个StackPanel的宽度,那很好:
PropertyInfo pi = stp.GetType().GetProperty("Width", BindingFlags.Public | BindingFlags.Instance);
if (null != pi)
{
pi.SetValue(stp, Convert.ChangeType("100", pi.PropertyType), null);
}
但是如果我想设置Margin.Left:
PropertyInfo pi = stp.GetType().GetProperty("Margin.Left", BindingFlags.Public | BindingFlags.Instance);
if (null != pi)
{
pi.SetValue(stp, Convert.ChangeType("100", pi.PropertyType), null);
}
它根本不起作用。 pi为空。我无法获得有效的PropertyInfo。 尝试获取有效的FieldInfo也会失败:
FieldInfo prop = stp.GetType().GetField("Margin.Left", BindingFlags.Public | BindingFlags.Instance);
if (null != prop)
{
prop.SetValue(stp, Convert.ChangeType("20", prop.FieldType));
}
答案 0 :(得分:0)
StackPanel
类没有名为“ Margin.Left”的属性。它具有一个Margin
属性,该属性返回一个Thickness
。并且Thickness
是一个值类型,因此,如果您只想更改左边距,您仍然需要创建一个新的Thickness
对象,并为其分配{{1}的Margin
属性}:
StackPanel