How do i make a listbox auto reflect every time i add or remove items from a SortedDictionary in WPF

69 Views Asked by At

I have a MainWindow, and an embedded sub window in the code behind for MainWindow. The embedded sub window also has it's own code behind file. The mainwindow has a listbox that i want to reflect each time the user double clicks on a list of strings found in the subwindow.

How do I go about doing this? I've looked into INotifyCollectionChanged but the documentation on msdn is extremely sparse.

Any help appreciated.

1

There are 1 best solutions below

1
On

You need to create wrapper class over SortedDictionary that implement INotifyCollectionChanged.

Simple example (of course you need to implement all methods of dictionary):

public class SyncSortedDictionary<T1,T2> : INotifyCollectionChanged, IDictionary<T1,T2>
{
    #region Fields

    private readonly SortedDictionary<T1,T2> _items;

    #endregion

    #region Events

    public event NotifyCollectionChangedEventHandler CollectionChanged;

    #endregion

    #region Notify

    private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index)
    {
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index));
    }

    private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index, int oldIndex)
    {
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index, oldIndex));
    }

    private void OnCollectionChanged(NotifyCollectionChangedAction action, object oldItem, object newItem, int index)
    {
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, newItem, oldItem, index));
    }

    private void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        var collectionChanged = CollectionChanged;

        if (collectionChanged == null)
            return;

        collectionChanged(this, e);
    }

    #endregion

    #region Public Methods

    public void Add(KeyValuePair<T1, T2> item)
    {
        int index = _items.Count;

        _items.Add(item.Key, item.Value);

        OnCollectionChanged(NotifyCollectionChangedAction.Add, item, index);
    }

    #endregion
}