我有一堂课
ObservableCollection<int>
作为属性,我正在尝试更改该类实例的该属性内的值。这是我拥有的代码,它得到了 TargetException:
object[] index = null;
var originalPropertyName = propertyName;
if (propertyName.Contains("[") && propertyName.Contains("]"))
{
index = new object[1];
index[0] = Convert.ToInt32(propertyName.Split('[')[1].Split(']')[0]);
propertyName = propertyName.Split('[')[0];
}
PropertyInfo pi = item.GetType().GetProperty(propertyName);
PropertyInfo opi = item.GetType().GetProperty(originalPropertyName);
Type pType = index != null ? pi.PropertyType.GetGenericArguments()[0] : pi.PropertyType;
if (pi != null)
{
object convertedValue = Convert.ChangeType(value, pType);
if (index == null)
{
item.GetType().GetProperty(propertyName).SetValue(item, convertedValue, null);
}
else
{
//PropertyInfo ipi = pi.PropertyType.GetProperties().Single(p => p.GetIndexParameters().Length > 0);
//var collection = pi.GetValue(item, index);
//collection.GetType().GetProperty("Value").SetValue(collection, convertedValue, null);
var _pi = pi.PropertyType.GetProperty("Item");
_pi.SetValue(pi, convertedValue, index);
}
}
上面没有显示 propertyName 是如何获得的,但是对于索引属性,它以“IndexedProperty[10]”的形式开始其生命周期。
在“其他”之后的评论中,您可以通过阅读其他一些 stackoverflow 帖子和其他论坛上有关如何执行此操作的信息来查看我尝试过的其他事情,但到目前为止我还失败了。有任何想法吗?
将属性转换为 ObservableCollection 是不可行的,因为我希望它是动态的。
整个事情的概念是通过更新每个实例的正确属性来拥有一个数据绑定的 DataGrid 并让粘贴正常工作,无论这些属性是否被索引。非索引属性工作正常,但我无法让 ObservableCollection 工作。