DataContext
Up to this point, I have alluded to the DataContext
property but haven’t discussed it
in depth. It is time to give it some attention by examining where it is
used, what it does, and how it can benefit a Silverlight
application.
The DataContext
property refers
to a source of data that you can bind to a target. The DataContext
often is set to an instance of an
entity, such as a Person
in the
previous examples. Once you set the DataContext
, you can bind it to any controls
that have access to it. For instance, you can use it to bind all
controls within a container control to a single data source. This
approach is useful when several controls use the same binding source. It
could become repetitive to indicate the binding source for every
control. Instead, you can set the DataContext
for the container of the
controls.
Each FrameworkElement
has a
DataContext
. This includes the
instances of the UserControl
class that the examples in
this chapter have demonstrated, as the UserControl
class inherits from the
Control
class, which in turn inherits
from the FrameworkElement
class. This
means that on a single UserControl
,
objects could be assigned to dozens of DataContext
properties of various
FrameworkElement
controls. For
example, the UserControl
, a layout control such as a
Grid
, and a series of interactive
controls such as TextBox
es, CheckBox
es, and ListBox
es might all have their DataContext
property
set.
DataContext and Source
You can assign the binding source via the Source
property ...
Get Data-Driven Services with Silverlight 2 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.