Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding in Label.ContentTemplate

Tags:

mvvm

binding

wpf

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>
like image 930
Mark Bostleman Avatar asked Aug 29 '10 16:08

Mark Bostleman


1 Answers

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"/>
like image 71
Quartermeister Avatar answered Sep 29 '22 04:09

Quartermeister