Share via


A better List for databinding

Have to thank DanteG for this tip ( blogs.msdn.com/danteg ).  Another quick gotcha in my quest for a heavily databound app.  Got a code-behind data file and want to organize the data such that it binds to the contents of a listbox?  Use a list -- right?  Actually, that depends. 

Will the List be changing during the use of the application?  In my application, we see here a list of characters, which is databound to a List in a C# class.

Clicking on the "Create New" button adds a new Character object to the list.  To my surprise, this part of databinding didn't "Just work."  Just another thing that I chalk up to it all being very convenient black magic.  The issue is that there was no change notification going on.  I could tell through debugging that after hitting the button, there were in fact five characters in the list, but the ListBox didn't seem to care very much.... unless I did an action that caused the ListBox to be bound to a different list, and then switched back, at which point I could see my new character.

Well, I could go through the pain of learning how to make listener notifications, but... that's so... so... "Programming HLL 1.0," as I call it.  Well, maybe I should say HLL 2.0, as C is nominally a high level language, but it looks a lot like assembly to my generation of programmers (I have done both, and C isn't nearly as bad as assembly... it just felt that way after going back from a managed-memory language like Java or C#).  I was "born" in the 2.0 langs, where you could pull this kind of thing off and do the notification, but it would be a pain.  Thankfully, I now work in what I call HLL 3.0, and there is a class for just this kind of thing. 

Realizing that, when not acting like black magic, databinding was a powerful feature of WPF, the C# gurus realized that we programmers would love to have a class that "just worked" with this kind of thing. 

I introduce the ObservableCollection.  It acts exactly like a List except that you can't do an AddRange operation, or anything else that manipulates a bunch of objects at once.  An ObservableCollection notifies anybody databound to it of every change.  In the case of my little character list, every press of the button immediately creates a new character and adds it to the ObservableCollection AND the ListBox.

Isn't it just lovely when things work?  My black magic skills have leveled up, methinks.  You won't believe the dark arts needed in my next post...

Comments