0
在設計時,我的控件應該公開數據源中可用的所有字段。例如,考慮數據源的下列結構在CurrencyManager中獲取數據源的屬性
List<Data> dataSource = new List<Data>()
dataSource.add(new Data(){ Value = 1, Rect = new Rectangle(10, 10, 10, 10)})
我想將控制結合在如矩形的"Left"
屬性的數據源的內部屬性。我用下面的代碼來實現這一點
var prop = this.BindingContext[dataSource];
ArrayList result = (ArrayList)GetPropertiesList(prop.Current, string.Empty);
爲GetPropertiesList方法的代碼是下面
private IList GetPropertiesList(object source, string parent)
{
ArrayList result = new ArrayList();
ArrayList innerProperties = new ArrayList();
Type sourceType = source.GetType();
PropertyInfo[] propertyInfo = sourceType.GetProperties();
if (parent != string.Empty)
parent += ".";
foreach (PropertyInfo info in propertyInfo)
{
object value = info.GetValue(source, null);
if(value == null)
result.Add(parent + info.Name);
else if (value is string || value is DateTime || value.GetType().IsPrimitive)
result.Add(parent + info.Name);
else
innerProperties = (ArrayList)(GetPropertiesList(value, parent + info.Name));
}
if(innerProperties.Count > 0)
result.AddRange(innerProperties);
return result;
}
當在列表對象(dataSource
)沒有添加的數據此代碼失敗。
請分享你的想法和意見