Saturday, January 9, 2016

The differences between TextBlock and Label in WPF

You can use two elements to show text in GUI, so-called "Label". These are
  • Label: <Label>Text</Label>
  • TextBlock: <TextBlock>Text</TextBlock>
Both produce nearly the same result. But there are differences. TextBlock inherits from FrameworkElement whereas Label inherits from ContentControl --> Control --> FrameworkElement.

This difference lead to all differences that these elements have.

One consequence can directly shown if we rewrite the code from above.
  • Label: <Label Content="Text" />
  • TextBlock: <TextBlock Text="Text" />
TextBlock has no Content, just Text. So TextBlock is restricted to strings, while Label can also have other types as content like images.
<Label>
    <Image Source="text.png" />
</Label>
One other frequently mentioned consequence from the different roots of Label and TextBlock is that Label supports Access Keys (Mnemonics), while TextBlock don't.
<Label Content="_Text"
       Target="{Binding ElementName=InputField}" />
<TextBox x:Name="InputField" />

Furthermore a Label is grayed out, if its IsEnabled property is false, whereas TextBlock isn't. You can also use the Template property for a custom control template or the ContentTemplate property to apply a DataTemplate to its content.

Summarized you can say the difference is that with a Label you can do more than with a TextBlock. You can do whatever a ContentControl can do, while a TextBlock can only do what a FrameworkElement can do. But the huge advantage of the TextBlock is that it is much more lightweight.

So use TextBlock, whenever you just need text. If text is insufficient, use Label.