views:

126

answers:

1

Is there a simple way to create a BindingList wrapper (with projection), which would update as the original list updates?

For example, let's say I have a mutable list of numbers, and I want to represent them as hex strings in a ComboBox. Using this wrapper I could do something like this:

BindingList<int> numbers = data.GetNumbers();
comboBox.DataSource = Project(numbers, i => string.Format("{0:x}", i));

I could wrap the list into a new BindingList, handle all source events, update the list and fire these events again, but I feel that there is a simpler way already.

+1  A: 

I have just stumbled across this question and I realized I might post the code I ended up with.

Since I wanted a quick solution, I made a sort of a poor man's implementation. It works as a wrapper around an existing source list, but it creates a full projected list of items and updates it as needed. At first I hoped I could do the projection on the fly, as the items are accessed, but that would require implementing the entire IBindingList interface from scratch.

What is does: any updates to the source list will also update the target list, so bound controls will be properly updated.

What it does not do: it does not update the source list when the target list changes. That would require an inverted projection function and I didn't need that functionality anyway. So items must always be added, changed or removed in the source list.

Usage example follows. let's say we have a list of numbers, but we want to display their squared values in a data grid:

// simple list of numbers
List<int> numbers = new List<int>(new[] { 1, 2, 3, 4, 5 });

// wrap it in a binding list
BindingList<int> sourceList = new BindingList<int>(numbers);

// project each item to a squared item
BindingList<int> squaredList = new ProjectedBindingList<int, int>
    (sourceList, i => i*i);

// whenever the source list is changed, target list will change
sourceList.Add(6);
Debug.Assert(squaredList[5] == 36);

And here is the source code:

public class ProjectedBindingList<Tsrc, Tdest> 
    : BindingList<Tdest>
{
    private readonly BindingList<Tsrc> _src;
    private readonly Func<Tsrc, Tdest> _projection;

    public ProjectedBindingList(
        BindingList<Tsrc> source, 
        Func<Tsrc, Tdest> projection)
    {
        _projection = projection;
        _src = source;
        RecreateList();
        _src.ListChanged += new ListChangedEventHandler(_src_ListChanged);
    }

    private void RecreateList()
    {
        RaiseListChangedEvents = false;
        Clear();

        foreach (Tsrc item in _src)
            this.Add(_projection(item));

        RaiseListChangedEvents = true;
    }

    void _src_ListChanged(object sender, ListChangedEventArgs e)
    {
        switch (e.ListChangedType)
        {
            case ListChangedType.ItemAdded:
                this.InsertItem(e.NewIndex, Proj(e.NewIndex));
                break;

            case ListChangedType.ItemChanged:
                this.Items[e.NewIndex] = Proj(e.NewIndex);
                break;

            case ListChangedType.ItemDeleted:
                this.RemoveAt(e.NewIndex);
                break;

            case ListChangedType.ItemMoved:
                Tdest movedItem = this[e.OldIndex];
                this.RemoveAt(e.OldIndex);
                this.InsertItem(e.NewIndex, movedItem);
                break;

            case ListChangedType.Reset:
                // regenerate list
                RecreateList();
                OnListChanged(e);
                break;

            default:
                OnListChanged(e);
                break;
        }
    }

    Tdest Proj(int index)
    {
        return _projection(_src[index]);
    }
}

I hope someone will find this useful.

Groo