WPF自定义容器类

时间:2010-08-02 18:56:18

标签: mvvm

我正在尝试创建一个自定义容器类,在我的案例中包含ViewMappingEntry,所以我创建了一个继承Freezable并实现ICollection的类..但是当在Blend中创建实例并浏览它时我收到此错误:无法添加内容到'ViewModelMapping'类型的对象..

注意:它编译得很好,我在Visual Studio中没有错误,所以我缺少什么?

public class ViewModelMapping : Freezable, ICollection<MappingEntry>
{
    object locker = new object();

    List<MappingEntry> internalList = new List<MappingEntry>();

    #region ICollection<MappingEntry> Members

    public void Add(MappingEntry item)
    {
        if (this.IsFrozen || this.IsSealed)
            throw new InvalidOperationException("ViewModelMapping is frozen");
        lock (locker)
            internalList.Add(item);
    }

    public void Clear()
    {
        if (this.IsFrozen || this.IsSealed)
            throw new InvalidOperationException("ViewModelMapping is frozen");
        lock (locker)
            internalList.Clear();
    }

    public bool Contains(MappingEntry item)
    {
        lock (locker)
            return internalList.Contains(item);
    }

    public void CopyTo(MappingEntry[] array, int arrayIndex)
    {
        lock (locker)
            internalList.CopyTo(array, arrayIndex);
    }

    public int Count
    {
        get 
        {
            lock (locker)
                return internalList.Count;
        }
    }

    public bool IsReadOnly
    {
        get { return base.IsFrozen || base.IsSealed; }
    }

    public bool Remove(MappingEntry item)
    {
        if (this.IsFrozen || this.IsSealed)
            throw new InvalidOperationException("ViewModelMapping is frozen");
        lock (locker)
            return internalList.Remove(item);
    }

    #endregion

    #region IEnumerable<MappingEntry> Members

    public IEnumerator<MappingEntry> GetEnumerator()
    {
        lock (locker)
            return (IEnumerator<MappingEntry>)internalList.ToArray().GetEnumerator();
    }

    #endregion

    #region IEnumerable Members

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        lock (locker)
            return internalList.ToArray().GetEnumerator();
    }

    #endregion

    protected override Freezable CreateInstanceCore()
    {
        ViewModelMapping viewModelMapping = new ViewModelMapping();
        lock(locker)
            viewModelMapping.internalList = new List<MappingEntry>(this.internalList.ToArray());

        return viewModelMapping;
    }
}

1 个答案:

答案 0 :(得分:0)

在尝试了之后,我找到了一个解决方案,如果我实现了所有这些接口 - &gt; ICollection,IList,IList,ICollection,IEnumerable它开始在混合中工作。