TOC

This article is currently in the process of being translated into Ukrainian (~21% done).

Basic controls:

The Label control

Елемент Label, у найпростішій формі, буде дуже схожий на TextBlock, який ми використовували в іншій статті. Ви швидко помітите, що замість властивості Text Label має властивість Content. Причина в тому, що Label може розміщувати будь-який тип керування безпосередньо всередині себе, а не просто текст. Цей вміст також може бути рядком, хоча, як ви бачите в цьому першому і дуже простому прикладі:

<Window x:Class="WpfTutorialSamples.Basic_controls.LabelControlSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="LabelControlSample" Height="100" Width="200">
    <Grid>
		<Label Content="This is a Label control." />
	</Grid>
</Window>

Інша річ, яку ви могли б помітити, це те, що Label, за замовчуванням, має деяке заповнення, що дозволяє відтворювати текст в декількох пікселях від верхнього лівого кута. Це не стосується керування TextBlock, де вам доведеться вказувати його (контент) вручну.

У такому простому випадку, де вміст - це просто рядок, мітка фактично створить внутрішній текстовий блок і покаже ваш рядок у ньому.

The Label control vs. the TextBlock control

Так навіщо тоді використовувати Label? Ну, є кілька важливих відмінностей між Label і TextBlock. TextBlock дозволяє лише відображати текстовий рядок, а Label також дозволяє:

  • Specify a border
  • Render other controls, e.g. an image
  • Use templated content through the ContentTemplate property
  • Use access keys to give focus to related controls

The last bullet point is actually one of the main reasons for using a Label over the TextBlock control. Whenever you just want to render simple text, you should use the TextBlock control, since it's lighter and performs better than the Label in most cases.

Label and Access keys (mnemonics)

In Windows and other operating systems as well, it's common practice that you can access controls in a dialog by holding down the [Alt] key and then pressing a character which corresponds to the control that you wish to access. The character to press will be highlighted when you hold down the [Alt] key. TextBlock controls doesn't support this functionality, but the Label does, so for control labels, the Label control is usually an excellent choice. Let's look at an example of it in action:

<Window x:Class="WpfTutorialSamples.Basic_controls.LabelControlSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="LabelControlSample" Height="180" Width="250">
	<StackPanel Margin="10">
		<Label Content="_Name:" Target="{Binding ElementName=txtName}" />
		<TextBox Name="txtName" />
		<Label Content="_Mail:" Target="{Binding ElementName=txtMail}" />
		<TextBox Name="txtMail" />
	</StackPanel>
</Window>

The screenshot shows our sample dialog as it looks when the Alt key is pressed. Try running it, holding down the [Alt] key and then pressing N and M. You will see how focus is moved between the two textboxes.

So, there's several new concepts here. First of all, we define the access key by placing an underscore (_) before the character. It doesn't have to be the first character, it can be before any of the characters in your label content. The common practice is to use the first character that's not already used as an access key for another control.

We use the Target property to connect the Label and the designated control. We use a standard WPF binding for this, using the ElementName property, all of which we will describe later on in this tutorial. The binding is based on the name of the control, so if you change this name, you will also have to remember to change the binding.

Using controls as Label content

As already mentioned, the Label control allows you to host other controls, while still keeping the other benefits. Let's try an example where we have both an image and a piece of text inside the Label, while also having an access key for each of the labels:

<Window x:Class="WpfTutorialSamples.Basic_controls.LabelControlAdvancedSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="LabelControlAdvancedSample" Height="180" Width="250">
	<StackPanel Margin="10">
		<Label Target="{Binding ElementName=txtName}">
			<StackPanel Orientation="Horizontal">
				<Image Source="http://cdn1.iconfinder.com/data/icons/fatcow/16/bullet_green.png" />
				<AccessText Text="_Name:" />
			</StackPanel>
		</Label>
		<TextBox Name="txtName" />
		<Label Target="{Binding ElementName=txtMail}">
			<StackPanel Orientation="Horizontal">
				<Image Source="http://cdn1.iconfinder.com/data/icons/fatcow/16/bullet_blue.png" />
				<AccessText Text="_Mail:" />
			</StackPanel>
		</Label>
		<TextBox Name="txtMail" />
	</StackPanel>
</Window>

This is just an extended version of the previous example - instead of a simple text string, our Label will now host both and image and a piece of text (inside the AccessText control, which allows us to still use an access key for the label). Both controls are inside a horizontal StackPanel, since the Label, just like any other ContentControl derivate, can only host one direct child control.

The Image control, described later in this tutorial, uses a remote image - this is ONLY for demonstrational purposes and is NOT a good idea for most real life applications.

Summary

In most situations, the Label control does exactly what the name implies: It acts as a text label for another control. This is the primary purpose of it. For most other cases, you should probably use a TextBlock control or one of the other text containers that WPF offers.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!