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.
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
IBindingListinterface 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:
And here is the source code:
I hope someone will find this useful.