10

我有一堂课

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 工作。

4

2 回答 2

13

具有ObservableCollection<int>as 属性的类实际上并不具有传统意义上的索引器的索引属性。它只是有一个非索引属性,它本身有一个索引器。因此,您需要使用GetValueto start with(不指定索引),然后在结果上获取索引器。

基本上,您需要记住:

foo.People[10] = new Person();

相当于:

var people = foo.People; // Getter
people[10] = new Person(); // Indexed setter

看起来你几乎已经有了这个注释掉的代码:

//var collection = pi.GetValue(item, index);
//collection.GetType().GetProperty("Value").SetValue(collection, convertedValue, null);

...但是您在错误的位置应用了索引。你想要(我认为 - 问题不是很清楚):

var collection = pi.GetValue(item, null);
collection.GetType()
          .GetProperty("Item") // Item is the normal name for an indexer
          .SetValue(collection, convertedValue, index);
于 2012-12-27T10:11:21.753 回答
0

试试这个,我不确定它是否会起作用

_pi.SetValue(pi, convertedValue, new object[] { (int) 0 }); 

//where 0 is the index in which you want to insert the value, in this case to index 0
于 2012-12-27T10:15:13.900 回答