返回项目i + 1而不是列表中的项目i

时间:2013-11-03 18:11:47

标签: c# .net class observablecollection

我有一些对象列表。如下所示:

public ObservableCollection<Property > Items { get; private set; }

现在我需要客户问项目i,而不是我发送项目i + 1。列表填写时我不可能改变安排。当用户呼叫Items而不是i时,它们也不可能调用i + 1。

所以最好的方法是我覆盖此属性的get方法,而不是i的索引中的对象返回i + 1索引中的对象。有可能吗?

1 个答案:

答案 0 :(得分:1)

根据建议,您可以根据ObservableCollection<T>创建自己的集合类型,并相应地修改索引器。唯一的问题是你不能只是覆盖索引器,因为它不是虚拟的,但你可以将ObservableCollection<T>包装到一个类中,将所有工作委托给它,但是修改索引器实现以将一个添加到获取访问权限:

public class PlusOneObservableCollection<T> : IList<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
    private ObservableCollection<T> innerCollection;

    public PlusOneObservableCollection()
    {
        this.innerCollection = new ObservableCollection<T>();
        this.innerCollection.CollectionChanged += InnerCollection_CollectionChanged;
    }
    public PlusOneObservableCollection(IEnumerable<T> collection)
    {
        this.innerCollection = new ObservableCollection<T>(collection);
        this.innerCollection.CollectionChanged += InnerCollection_CollectionChanged;
    }

    private void InnerCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        NotifyCollectionChangedEventHandler handler = this.CollectionChanged;
        if (handler != null)
        {
            handler(this, e);
        }
    }

    public int IndexOf(T item)
    {
        return this.innerCollection.IndexOf(item);
    }

    public void Insert(int index, T item)
    {
        this.innerCollection.Insert(index, item);
    }

    public void RemoveAt(int index)
    {
        this.innerCollection.RemoveAt(index);
    }

    public T this[int index]
    {
        get
        {
            //Here is where the actual change takes place
            return this.innerCollection[index + 1];
        }
        set
        {
            this.innerCollection[index] = value;
        }
    }

    public void Add(T item)
    {
        this.innerCollection.Add(item);
    }

    public void Clear()
    {
        this.innerCollection.Clear();
    }

    public bool Contains(T item)
    {
        return this.innerCollection.Contains(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        this.innerCollection.CopyTo(array, arrayIndex);
    }

    public int Count
    {
        get { return this.innerCollection.Count; }
    }

    public bool IsReadOnly
    {
        get { return false; }
    }

    public bool Remove(T item)
    {
        return this.innerCollection.Remove(item);
    }

    public IEnumerator<T> GetEnumerator()
    {
        return this.innerCollection.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.innerCollection.GetEnumerator();
    }

    public event NotifyCollectionChangedEventHandler CollectionChanged;
    public event PropertyChangedEventHandler PropertyChanged;
}

使用这种方法,您需要更改属性类型,因为它不再从ObservableCollection<T>继承,而是从IList<T>继承。然而,让它实现INotifyCollectionChanged接口可以让用户订阅更改通知。