WPF ObservableCollection <T> vs BindingList <T>

Fla*_*ack 11 c# data-binding wpf infragistics observablecollection

在我的WPF应用程序中,我有一个XamDataGrid.网格绑定到ObservableCollection.我需要允许用户通过网格插入新行,但事实证明,为了使"添加新行"行可用,xamDataGrid的源需要实现IBindingList.ObservableCollection不实现该接口.

如果我将我的源代码更改为BindingList,它可以正常工作.但是,根据我在阅读这个主题时可以理解的,BindingList实际上是一个WinForms的东西,在WPF中并不完全支持.

如果我将所有ObservableCollections更改为BindingLists,我会犯错吗?有没有人有任何其他建议,我如何为我的xamDataGrid添加新的行功能,同时将源保持为ObservableCollection?我的理解是,有许多不同的网格需要实现IBindingList才能支持添加新的行功能,但我看到的大多数解决方案只是切换到BindingList.

谢谢.

Opp*_*nal 5

IBindingList接口和BindingList类是在 System.ComponentModel 命名空间中定义的,因此与 Windows 窗体不严格相关

您是否检查过xamGrid是否支持绑定到ICollectionView源?如果是这样,您可以使用此接口公开数据源并使用BindingListCollectionView支持它。

您还可以创建 IBindingList 接口的子类ObservableCollection<T>并实现 IBindingList 接口:

using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;

public class ObservableBindingList<T> : ObservableCollection<T>, IBindingList
{
    //  Constructors
    public ObservableBindingList() : base()
    {
    }

    public ObservableBindingList(IEnumerable<T> collection) : base(collection)
    {
    }

    public ObservableBindingList(List<T> list) : base(list)
    {
    }

    //  IBindingList Implementation
    public void AddIndex(PropertyDescriptor property)
    {
        throw new NotImplementedException();
    }

    public object AddNew()
    {
        throw new NotImplementedException();
    }

    public bool AllowEdit
    {
        get { throw new NotImplementedException(); }
    }

    public bool AllowNew
    {
        get { throw new NotImplementedException(); }
    }

    public bool AllowRemove
    {
        get { throw new NotImplementedException(); }
    }

    public void ApplySort(PropertyDescriptor property, ListSortDirection direction)
    {
        throw new NotImplementedException();
    }

    public int Find(PropertyDescriptor property, object key)
    {
        throw new NotImplementedException();
    }

    public bool IsSorted
    {
        get { throw new NotImplementedException(); }
    }

    public event ListChangedEventHandler ListChanged;

    public void RemoveIndex(PropertyDescriptor property)
    {
        throw new NotImplementedException();
    }

    public void RemoveSort()
    {
        throw new NotImplementedException();
    }

    public ListSortDirection SortDirection
    {
        get { throw new NotImplementedException(); }
    }

    public PropertyDescriptor SortProperty
    {
        get { throw new NotImplementedException(); }
    }

    public bool SupportsChangeNotification
    {
        get { throw new NotImplementedException(); }
    }

    public bool SupportsSearching
    {
        get { throw new NotImplementedException(); }
    }

    public bool SupportsSorting
    {
        get { throw new NotImplementedException(); }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以子类化BindingList<T>并实现INotifyCollectionChanged接口。