views:

15

answers:

1

In the Xaml below, the first control (the TextBlock by itself) has no problem binding and rendering the value of RecordCount. But in the second control (the Label with the ContentTemplate), the value of RecordCount is not rendered. However, the literal "Cars" is rendered fine. So I know the ContentTemplate is working, but the binding to RecordCount from within the ContentTemplate is not. What am I doing wrong?

<TextBlock Text="{Binding RecordCount}"/>

<Label HorizontalAlignment="Center" >
     <Label.ContentTemplate>
          <DataTemplate>
               <StackPanel Orientation="Horizontal" Width="100">
                    <TextBlock Text="{Binding RecordCount}"/>
                    <TextBlock Text=" Cars"/>
               </StackPanel>
          </DataTemplate>
     </Label.ContentTemplate>
</Label>
+1  A: 

Set the Content property on the Label to the current DataContext:

<Label HorizontalAlignment="Center" Content="{Binding}">

or, set the StackPanel as the Content and don't use a template at all:

<Label HorizontalAlignment="Center">
    <StackPanel Orientation="Horizontal" Width="100">
        <TextBlock Text="{Binding RecordCount}"/>
        <TextBlock Text=" Cars"/>
    </StackPanel>
</Label>

The ContentTemplate is used to present the Content. Since it is null, the DataContext is null when your template is instantiated. The TextBlocks are still created, so Cars is rendered, but null doesn't have a RecordCount property so the first text block is rendered with no text.

Also, if you are only using two TextBlocks to concatenate text, you can use the StringFormat property in .NET 3.5 SP1 or later:

<Label Content="{Binding RecordCount}" ContentStringFormat="{}{0} Cars"/>
Quartermeister
First, thanks for the solution. More importantly, thanks for the explanation. I totally get the mechanics now. But I'll have to save that understanding for another day because, yes, the ContentStringFormat is what I need - I didn't even know that existed. Thanks again!
MarkB