如何在C#中的DataGrid中使自定义集合可编辑

时间:2018-10-24 10:21:11

标签: c# wpf data-binding

我有一个业务对象类,其中包含其他业务对象的List<T>定义。

我无法更改类结构,因此不能简单地使用ObservableCollection<T>而不是List<T>,但我想利用ObservableCollection<T>功能。因此,我像这样创建了一个可观察的集合包装器类(也使用IList<T>而不是ICollection<T>进行了尝试)。

public class CollectionObservableOverlay<T> : ICollection<T>, INotifyCollectionChanged
{
    protected ICollection<T> _wrappedCollection;

    #region ICollection<T> properties
    public int Count { get { return _wrappedCollection.Count; } }

    public bool IsReadOnly { get { return _wrappedCollection.IsReadOnly; } }
    #endregion

    public event NotifyCollectionChangedEventHandler CollectionChanged;

    public CollectionObservableOverlay(ICollection<T> wrappedCollection)
    {
        _wrappedCollection = wrappedCollection;
    }

    protected void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        CollectionChanged?.Invoke(this, e);
    }

    #region ICollection<T> methods

    public void Add(T item)
    {
        _wrappedCollection.Add(item);
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));

    }

    public void Clear()
    {
        _wrappedCollection.Clear();
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }

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

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

    public virtual bool Remove(T item)
    {
        bool removed = _wrappedCollection.Remove(item);
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        return removed;
    }

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

    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable)_wrappedCollection).GetEnumerator();
    }
    #endregion
}

问题是,当我将CollectionObservableOverlay的实例绑定为DataGridItemsSource并尝试编辑项目时,出现以下错误:

System.InvalidOperationException
  HResult=0x80131509
  Message='EditItem' is not allowed for this view.
  Source=PresentationFramework

我尝试直接绑定到基础集合,这对于DataGrid的编辑工作很好,因此基础列表或其包含的对象不应成为问题的根源。

我的猜测是,我缺少一些以具体List<T>类型实现的功能,但在IList<T>ICollection<T>接口中不存在。

我阅读了thisother related的问题和答案,但是没有一个人提供解决方案,甚至没有可能。据我了解,提供给DataGrid的{​​{3}}应该实现ICollectionView,但是我不知道如何实现这种行为。欢迎任何帮助。

1 个答案:

答案 0 :(得分:1)

您的源集合必须实现非通用的IList接口,才能使DataGrid控件的内部编辑功能正常工作。

List<T>ObservableCollection<T>可以做到这一点,但HashSet<T>并非如此。