数据绑定排序的ComboBox

时间:2012-06-25 16:46:40

标签: wpf data-binding combobox observablecollection

我有一个带有许多ComboBox的WPF应用程序。每个ComboBox都绑定到一个SortedList,让我们称之为数据源。我为数据源选择这种类型的原因仅仅是因为我将获得TValues的更新和新项目,并且可能删除它们,尽管它们不太可能。我希望在数据事件(添加,更新,删除发生)时更快更容易地找到项目。然后我绑定到IList类型的属性并在getter中返回_mySortedList.Values。

然而,我很快意识到这不会起作用,因为我没有像使用ObservableCollection那样收到有关更改的通知。

所以我想知道将所有项目排序的最佳方法是什么(排序条件永远不会改变但可以基于对象的多个属性)并且具有ObservableCollection的良好自动通知。

非常感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:1)

最简单的方法是创建一个实现INotifyCollectionChanged的子类,并且还具有Sort功能。如果您已经在使用SortedList,那么您只需创建一个派生自SortedList的类,实现INotifyCollectionChanged并覆盖Add / Remove / etc。引发NotifyCollectedChanged事件的方法。

它可能看起来像这样(不完整):

public class SortedObservableList : SortedList, INotifyCollectionChanged
{
    public override void Add(object key, object value)
    {
        base.Add(key, value);
        RaiseCollectionChanged(NotifyCollectionChangedAction.Add);
    }

    public override void Remove(object key)
    {
        base.Remove(key);
        RaiseCollectionChanged(NotifyCollectionChangedAction.Remove);
    }

    #region INotifyCollectionChanged Members

    protected void RaiseCollectionChanged(NotifyCollectionChangedAction action)
    {
        if (CollectionChanged != null)
            CollectionChanged(this, new NotifyCollectionChangedEventArgs(action));
    }

    public event NotifyCollectionChangedEventHandler CollectionChanged;

    #endregion
}

或者,您可以创建一个派生自ObservableCollection的类并实现排序功能,但如果您已经使用了SortedList,则可能没有意义。

编辑:您在下面的评论以及对该问题的进一步审核表明您使用的是SortedList(SortedList)的通用版本。在这种情况下,您可以让SortableObservableList实现IDictionary接口(和/或ICollection,IEnumerable),并在内部使用SortedList来存储项目。下面是您可以使用的代码片段(不包括所有已实现的方法,因为它们只是传递到您的内部排序列表。)

public class SortedObservableList<TKey, TValue> : IDictionary<TKey, TValue>, INotifyCollectionChanged
{
    private SortedList<TKey, TValue> _list;

    public SortedObservableList()
    {
        _list = new SortedList<TKey, TValue>();
    }

    #region INotifyCollectionChanged Members

    protected void RaiseCollectionChanged(NotifyCollectionChangedAction action)
    {
        if (CollectionChanged != null)
            CollectionChanged(this, new NotifyCollectionChangedEventArgs(action));
    }

    public event NotifyCollectionChangedEventHandler CollectionChanged;

    #endregion

    #region IDictionary<TKey,TValue> Members

    public void Add(TKey key, TValue value)
    {
        _list.Add(key, value);
        this.RaiseCollectionChanged(NotifyCollectionChangedAction.Add);
    }

    public bool ContainsKey(TKey key)
    {
        return _list.ContainsKey(key);
    }

    public ICollection<TKey> Keys
    {
        get { return _list.Keys; }
    }

    public bool Remove(TKey key)
    {
        bool result = _list.Remove(key);
        this.RaiseCollectionChanged(NotifyCollectionChangedAction.Remove);
        return result;
    }

    //etc...

    #endregion
}
相关问题