开发者

Binding in Label.ContentTemplate

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 kn开发者_开发知识库ow 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>


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"/>


Just an alternative, you can bind the RecordCount to Label's Content and have DataTemplate takes care on how you are going to show it.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜