What the hell is a DataContext anyway?

DataContext, DataSource, DomainDataSource, DomainDataContext… what are they, how do they relate and how do you use them together to perform binding in Silverlight?

A DataContext can by anything. More specifically, it can be any type of object. Any IEnumerable is an object, and if you set some IEnumerable as the DataContext of a Grid and pepper the grid with widgets then you can bind the widgets to the properties of the objects in the collection, so if it’s a collection of Foo and Foo has properties A and B, then you can bind textBoxA and textBoxB to A and B with “{Binding Path=A}” and “{Binding Path=B}” respectively.

Each and every bindable widget has a DataContext property. Generally you don’t set this, because it’s what Microsoft has taken to calling a DependencyProperty, which is the same as an ambient property, which is to say the value is “inherited” from the widget’s container widget unless you set it explicitly. So if you have a grid that contains textBoxA and textBoxB, then you only need to set the DataContext for the grid, but you need to set the Path part of the binding explicitly for each widget.

Actually if you think about it what I just wrote cannot be true; the DataContext for the grid’s widgets would have to be the CurrentItem of the grid’s DataContext, and that’s exactly right. It is.

So what’s this CurrentItem business? Well, when you “set” the DataContext property on a widget, it’s not a pure assignment. A wrapper object is created (a derivative of the class DataContext, in fact) and for collections this is a sort of cursor.

I haven’t checked this particular thought yet but it just came to me that things which aren’t collections could be treated as collections of one item, by the simple expedient of constructing such a collection. This would make the CurrentItem the only item, obviating the need for different binding logic. It’s certainly what I would do, having thought of it, as I just did. I bet they did, it’s so elegant.

So there you have it. Now that I know this stuff data binding in Silverlight has suddenly become really straightforward, although we’ll see whether I’m still singing that song in a couple of days.

Published 12-17-2009 23:07 by peterw