Silverlight controls support binding to data, whether it be
a single or collection of business objects, or a DataTable. How you bind,
though, depends on the control you are using. Some controls may implement an
ItemsSource property. This property comes from a special base class in the
Silverlight framework, and won't be discussed here. This type of control is
more for controls that have a repeatable interface (like the ListBox).
However, controls that do not implement this property can also be bound.
By default, controls can be supplied an underlying data
source via the DataContext property. This property specifies an object or
collection that acts as the relative data source, or the data that's associated
with the control. What does that mean in the case of the
HeaderedContentControl? Let's take a look.
One of the ways to supply this value is via code, as in
Listing 3. I like to reference my data via code, and skip the inline
capabilities of referencing data.
Listing 3: Supplying a DataContext
This.HeaderedControlInstance.DataContext = myObj;
This control now knows about the object being referred to it.
So any {Binding} statements within the header and content templates come from
data supplied from the object assigned to DataContext.
However, if you tried to implement this as is based on my
description of the solution, and expect it to work, it won't bind correctly (it
appears blank). This is because there is one other step that needs to happen.
A generic {Binding} statement needs assigned to the Header and Content
properties; this correctly passes the underlying object supplied to the
DataContext property to the header/content templates. The final representation
of the control would appear as:
Listing 4: Binding in the Header/Content Templates
<HeaderedContentControl Header="{Binding}" Content="{Binding}">
<HeaderedContentControl.HeaderTemplate>
<Label Content="{Binding Title}" />
</HeaderedContentControl.HeaderTemplate>
<HeaderedContentControl.ContentTemplate>
<Label Content="{Binding Text}" />
</HeaderedContentControl.ContentTemplate>
</HeaderedContentControl>
In Listing 4, the Headered Content Control receives an
object (via the DataContext) that has a Title and Text property, which is
supplied to the Header/Content templates via the binding in the Header/Content
properties. The Title and Text values in the bound object are bound to labels,
via the Binding statement. The value in the Binding declaration has to match
the property in the underlying object.
So what's the difference between "{Binding}" and
"{Binding Title}"? In the latter option, Title has to be the name of
a property that's being bound to some control. The binding statement without a
parameter, the former option, binds the whole object to the control. So the
whole object is bound to the Header/Content of the control, so individual properties
can be bound.