I feel stupid but cannot find out how to add a text to a WPF Label control in code. Like following for a TextBlock:
DesrTextBlock.Text = "some text";
What is equivalent property in Label for doing it?
DesrLabel.??? = "some text"; //something like this
asked Feb 4, 2011 at 20:11
Try DesrLabel.Content
. Its the WPF way.
answered Feb 4, 2011 at 20:14
Daniel A. WhiteDaniel A. White
185k46 gold badges364 silver badges439 bronze badges
5
In normal winForms, value of Label object is changed by,
myLabel.Text= "Your desired string";
But in WPF Label control, you have to use .content property of Label control
for example,
myLabel.Content= "Your desired string";
answered Dec 15, 2012 at 18:18
Utkal SinhaUtkal Sinha
3313 silver badges2 bronze badges
0
I believe you want to set the Content
property. This has more information on what is available to a label.
answered Feb 4, 2011 at 20:14
Mark AveniusMark Avenius
13.5k6 gold badges41 silver badges50 bronze badges
You can use the Content property on pretty much all visual WPF controls to access the stuff inside them. There’s a heirarchy of classes that the controls belong to, and any descendants of ContentControl will work in this way.
answered Feb 4, 2011 at 20:18
RichardW1001RichardW1001
1,98513 silver badges22 bronze badges
you can use TextBlock control and assign the text property.
answered Feb 4, 2011 at 20:16
Davide PirasDavide Piras
43.7k10 gold badges95 silver badges146 bronze badges
do not forgat to add x:name to your MainWindow.xaml
answered Jan 25 at 19:17
Label myLabel = new Label ();
myLabel.Content = "Hello World!";
answered Aug 7, 2015 at 12:59
mitomito
618 bronze badges
1
trolol 2 / 2 / 0 Регистрация: 22.01.2012 Сообщений: 56 |
||||
1 |
||||
02.02.2012, 19:49. Показов 12740. Ответов 7 Метки нет (Все метки)
Добрый вечер =) вот возник вопрос, как поменять контент у label’а?
Кстати может кто сказать, что мол я класс не вызываю newClass или в нем функцию =) Все работает и вызывается, если что
__________________
0 |
717 / 708 / 168 Регистрация: 15.06.2011 Сообщений: 1,704 |
|
02.02.2012, 19:57 |
2 |
Проверь модификатор доступа у Label, он должен быть public.
0 |
SpiritRI 83 / 83 / 10 Регистрация: 20.05.2011 Сообщений: 145 |
||||||||
02.02.2012, 20:03 |
3 |
|||||||
Добавлено через 4 минуты
0 |
trolol 2 / 2 / 0 Регистрация: 22.01.2012 Сообщений: 56 |
||||
02.02.2012, 21:19 [ТС] |
4 |
|||
Проверь модификатор доступа у Label, он должен быть public. Да вроде как паблик, где я проверю? и ведь не объявляю ее как переменную (просто в конструкторе создал)
(MainWindow)Application.Current.MainWindow; увы, но не работает.. Добавлено через 58 минут
0 |
Dj_SheLL 180 / 85 / 10 Регистрация: 13.02.2010 Сообщений: 318 |
||||
03.02.2012, 09:01 |
5 |
|||
увы, но не работает.. Забудь про вложенные классы, это просто декоративное украшение… Держи,работает (без манипуляций с public-private с label):
0 |
trolol 2 / 2 / 0 Регистрация: 22.01.2012 Сообщений: 56 |
||||
03.02.2012, 11:07 [ТС] |
6 |
|||
Забудь про вложенные классы, это просто декоративное украшение… Держи,работает (без манипуляций с public-private с label):
Спасибо большое! =) Добавлено через 24 минуты Добавлено через 11 минут
0 |
Dj_SheLL 180 / 85 / 10 Регистрация: 13.02.2010 Сообщений: 318 |
||||||||
03.02.2012, 11:14 |
7 |
|||||||
а я пытаюсь это сдедать через класс И в чём проблема? Вызывайте функцию где хотите,при чём тут кнопка. Пример таймера:
Вызов в любом месте (2 секунды):
1 |
trolol 2 / 2 / 0 Регистрация: 22.01.2012 Сообщений: 56 |
||||
03.02.2012, 11:23 [ТС] |
8 |
|||
В общем разобрался, всем спасибо за внимание!
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
03.02.2012, 11:23 |
8 |
- Remove From My Forums
-
Question
-
Hi, I’m creating simple app for my son for math practice. It is also for me to practice C# as I started 2 weeks ago.
I got to a problem when Label is not updated with GOOD or WRONG before regenare new equation.
Could someone help please?
public MainWindow() { InitializeComponent(); CHECK.IsEnabled = false; } public int check; public int number1; public int number2; public int correct; public int wrong; private void CHECK_Click(object sender, RoutedEventArgs e) { CHECK.IsEnabled = false; StartButton.IsEnabled = true; int suma = number1 + number2; if (Convert.ToInt32(input.Text) == suma) { num1.Content = "GOOD!"; } else { num1.Content = "WRONG!"; } Thread.Sleep(2000); input.Text = ""; Numbers(); } private void Numbers() { Random GetRandom = new Random(); number1 = GetRandom.Next(1, 11); number2 = GetRandom.Next(1, number1); num1.Content = number1 + " + " + number2; StartButton.IsEnabled = false; CHECK.IsEnabled = true; } private void Start(object sender, RoutedEventArgs e) { Numbers(); } private void Button_Click(object sender, RoutedEventArgs e) { this.Close(); }
-
Moved by
Monday, June 26, 2017 5:39 AM
WPF question
-
Moved by
Текстовые элементы управления
Последнее обновление: 18.01.2016
TextBlock
Элемент предназначен для вывода текстовой информации, для создания простых надписей:
<StackPanel> <TextBlock>Текст1</TextBlock> <TextBlock Text="Текст2" /> </StackPanel>
Ключевым свойством здесь является свойство Text
, которое задает текстовое содержимое. Причем в случае <TextBlock>Текст1</TextBlock>
данное свойство задается неявно.
С помощью таких свойств, как FontFamily, TextDecorations и др., мы можем настроить отображение текста. Однако мы можем задать и более сложное форматирование, например:
<TextBlock TextWrapping="Wrap"> <Run FontSize="20" Foreground="Red" FontWeight="Bold">О</Run> <Run FontSize="16" Foreground="LightSeaGreen">негин был, по мненью многих...</Run> </TextBlock>
Элементы Run
представляют куски обычного текста, для которых можно задать отдельное форматирование.
Для изменения параметров отображаемого текста данный элемент имеет такие свойства, как LineHeight,
TextWrapping и TextAlignment.
Свойство LineHeight позволяет указывать высоту строк.
Свойство TextWrapping позволяет переносить текст при установке этого свойства TextWrapping="Wrap"
. По умолчанию это свойство имеет
значение NoWrap
, поэтому текст не переносится.
Свойство TextAlignment выравнивает текст по центру (значение Center), правому (Right) или левому краю (Left): <TextBlock TextAlignment="Right">
Для декорации текста используется свойство TextDecorations, например, если TextDecorations="Underline"
, то текст будет подчеркнут.
Если нам вдруг потребуется перенести текст на другую строку, то тогда мы можем использовать элемент LineBreak
:
<TextBlock> Однажды в студеную зимнюю пору <LineBreak /> Я из лесу вышел </TextBlock>
TextBox
Если TextBlock просто выводит статический текст, то этот элемент представляет поле для ввода текстовой информации.
Он также, как и TextBlock, имеет свойства TextWrapping, TextAlignment и TextDecorations.
С помощью свойства MaxLength можно задать предельное количество вводимых символов.
<TextBox MaxLength="250" TextChanged="TextBox_TextChanged">Начальный текст</TextBox>
В коде C# мы можем обработать событие изменения текста:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { TextBox textBox = (TextBox)sender; MessageBox.Show(textBox.Text); }
По умолчанию, если вводимый текст превышает установленные границы поля, то текстовое поле растет, чтобы вместить весь текст. Но визуально это не очень
хорошо выглядит. Поэтому, как и в случае с TextBlock, мы можем перенести непомещающийся текст на новую строку, установив свойство
TextWrapping=»Wrap».
Чобы переводить по нажатию на клавишу Enter курсор на следующую строку, нам надо установить свойство AcceptsReturn="True"
.
Также мы можем добавить полю возможность создавать табуляцию с помощью клавиши Tab, установив свойство AcceptsTab="True"
Для отображения полос прокрутки TextBox поддерживает свойства VerticalScrollBarVisibility и НоrizontalScrollBarVisibility:
<TextBox AcceptsReturn="True" Height="100" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">Начальный текст</TextBox>
Возможно, при создании приложения нам потребуется сделать текстовое поле недоступным для ввода (на время в зависимости от условий или вообще),
тогда для этого нам надо установить свойство IsReadOnly="True"
.
Для выделения текста есть свойства SelectionStart, SelectionLength и SelectionText.
Например, выделим программно текст по нажатию кнопки:
<StackPanel> <TextBox x:Name="textBox1" Height="100" SelectionBrush="Blue" /> <Button Content="Выделить текст" Height="30" Width="100" Click="Button_Click" Margin="10" /> </StackPanel>
Обработчик нажатия кнопки:
private void Button_Click(object sender, RoutedEventArgs e) { textBox1.SelectionStart = 5; textBox1.SelectionLength = 10; textBox1.Focus(); // данное выражение эквивалентно //textBox1.Select(5, 10); }
Проверка орфографии
TextBox обладает встроенной поддержкой орфографии. Чтобы ее задействовать, надо установить свойство SpellCheck.IsEnabled="True"
.
Кроме того, по умолчанию проверка орфографии распространяется только на английский язык, поэтому, если приложение заточено под другой язык, нам надо его
явным образом указать через свойство Language:
<DockPanel> <TextBox SpellCheck.IsEnabled="True" Language="ru-ru">Привет, как дила?</TextBox> </DockPanel>
Метка (Label)
Главной особенностью меток является поддержка мнемонических команд-клавиш быстрого доступа, которые передают фокус связанному элементу. Например,
<Label Target="{Binding ElementName=TextBox1}">_привет</Label> <TextBox Name="TextBox1" Margin="0 30 0 0" Height="30" Width="100"></TextBox>
Теперь, нажав на клавишу «п», мы переведем фокус на связанное текстовое поле. При вызове приложения подчеркивание не отображается, чтобы отображать подчеркивание, надо нажать на клавишу Alt.
Тогда чтобы перевести фокус на связанное текстовое поле необходимо будет нажать сочетание Alt + «п».
Если не предполагается использование клавиш быстрого доступа, то для вывода обычной текста вместо меток лучше использовать элемент TextBlock.
PasswordBox
Элемент предназначен для ввода парольной информации. По сути это тоже текстовое поле, только для ввода символов используется маска.
Свойство PasswordChar устанавливает символ маски, отображаемый при вводе пароля. Если это свойство не задано, то по умолчанию
для маски символа используется черная точка.
Свойство Password устанавливает парольную строку, отображаемую по умолчанию при загрузке окна приложения.
<StackPanel> <PasswordBox PasswordChar="*" MinHeight="30" /> <PasswordBox MinHeight="30" /> </StackPanel>
RichTextBox
Для вывода текстового содержимого, насыщенного форматированием, графикой, предназначен RichTextBox. Можно даже сказать, что он выводит не
просто текст, а документы с более сложным форматированием, чем обычный TextBox. Более подробно о нем, а также как на его основе создать
простой текстовый редактор, мы поговорим в главе, посвященной документам.
Hello folks, Today I will explain you regarding Label control in WPF. I have already explained you regarding how could we create new project of WPF and basic structure of WPF project.
Let’s try to understand regarding Label by using examples:
1. Create a Label
A Label is widely used WPF Control in XAML.
< Label Content="Hello"/>
2. Label With Font Styling
Below are the basic property of Label for Fonts:
- FontSize: Could set size of Font used in Label.
- FontWeight: Set Font size like Thin, ExtraLight, Light, Normal, Medium etc.
- FontStyle: Set Font style like Italic, Normal, Oblique.
- FontFamily: Set Font Family.
<!--Example - 2 for Label with font--> <Label FontSize="50" FontWeight="ExtraLight" FontStyle="Italic" FontFamily="SketchFlow Print" Content="Label with font"/>
3. Label with background color and canvas
Label’s Background and Foreground properties set the color of background and foreground of Label. Below is the code snippet for Background and Foreground along with Alignment property of Label.
<!--Example - 3 for Label with background color and canvas--> <Label Grid.Row="1" Content="Label with background color and canvas" Width="850" Height="50" Canvas.Left="10" Canvas.Top="100" FontSize="40" FontFamily="Georgia" FontWeight="Bold" Background="BlueViolet" Foreground="White" VerticalAlignment="Center" HorizontalAlignment="Center" />
4. Adding Controls to a WPF Label
We can use different WPF controls as a content in Label control as shown below code snippet.
<!--Example - 4 for Adding Controls to a WPF Label --> <Label Canvas.Left="10" Canvas.Top="50" Grid.Row="2"> <StackPanel Orientation="Horizontal"> <TextBlock Text="TextBlock 1," FontSize="40"/> <TextBlock Text="TextBlock 2," FontSize="40"/> <TextBlock Text="TextBlock 3" FontSize="40" /> </StackPanel> </Label>
5. Set Image as Background in a Label WPF
We can set background image as a background of Label using Background property of Label and ImageBrush.
<!--Example - 5 Set Image as Background in a Label WPF --> <Label Grid.Row="3"> <Label.Background> <ImageBrush ImageSource="WPF-image.PNG" /> </Label.Background> </Label>
6. Access keys/mnemonics in WPF Label
In Windows, it’s common practice that you can access controls without using mouse by holding down the [Alt] key and then pressing a any 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.
<!--Example - 6 Access keys/mnemonics in WPF Label --> <StackPanel Margin="10" Grid.Row="4"> <Label Content="_Mail:" Target="{Binding ElementName=txtMail}" /> <TextBox Name="txtMail" /> </StackPanel>
7. Access keys/mnemonics with Icon in WPF Label
Same as above example we can use image along with Access keys/mnemonics Label control in WPF as shown in below example
<!--Example - 7 Access keys/mnemonics with Icon in WPF Label --> <StackPanel Margin="10" Grid.Row="5"> <Label Target="{Binding ElementName=txtMail2}" > <StackPanel Orientation="Horizontal"> <Image Source="Email-icon.png" Width="25" Height="25" /> <AccessText Text="M_ail:" /> </StackPanel> </Label> <TextBox Name="txtMail2" /> </StackPanel>
8. Format a WPF Label using background and Gradient
The Background and Foreground properties of the Label set the background and foreground colors of a Label. You may use any brush to fill the border. The following code snippet uses linear gradient brushes to draw the background and foreground of a Label.
<!--Example - 8 Format a WPF Label using background and Gradient --> <Label Grid.Row="6"> <Label.Background> <LinearGradientBrush StartPoint="0,0" EndPoint="1,1"> <GradientStop Color="Pink" Offset="0.1" /> <GradientStop Color="Blue" Offset="0.25" /> <GradientStop Color="Green" Offset="0.75" /> <GradientStop Color="Red" Offset="1.0" /> </LinearGradientBrush> </Label.Background> <Label.Foreground> <LinearGradientBrush StartPoint="0,0" EndPoint="1,1"> <GradientStop Color="Orange" Offset="0.25" /> <GradientStop Color="Green" Offset="1.0" /> </LinearGradientBrush> </Label.Foreground> </Label>
9. Full source code with all examples
<Window x:Class="WpfLabel.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfLabel" mc:Ignorable="d" Title="Label Example in WPF" Height="650" Width="900"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <!--Example - 2 for Label with font--> <Label FontSize="50" FontWeight="ExtraLight" FontStyle="Italic" FontFamily="SketchFlow Print" Content="Label with font"/> <!--Example - 3 for Label with background color and canvas--> <Label Grid.Row="1" Content="Label with background color and canvas" Width="850" Height="50" Canvas.Left="10" Canvas.Top="100" FontSize="40" FontFamily="Georgia" FontWeight="Bold" Background="BlueViolet" Foreground="White" VerticalAlignment="Center" HorizontalAlignment="Center" /> <!--Example - 4 for Adding Controls to a WPF Label --> <Label Canvas.Left="10" Canvas.Top="50" Grid.Row="2"> <StackPanel Orientation="Horizontal"> <TextBlock Text="TextBlock 1," FontSize="40"/> <TextBlock Text="TextBlock 2," FontSize="40"/> <TextBlock Text="TextBlock 3" FontSize="40" /> </StackPanel> </Label> <!--Example - 5 Set Image as Background in a Label WPF --> <Label Grid.Row="3"> <Label.Background> <ImageBrush ImageSource="WPF-image.PNG" /> </Label.Background> </Label> <!--Example - 6 Access keys/mnemonics in WPF Label --> <StackPanel Margin="10" Grid.Row="4"> <Label Content="_Mail:" Target="{Binding ElementName=txtMail}" /> <TextBox Name="txtMail" /> </StackPanel> <!--Example - 7 Access keys/mnemonics with Icon in WPF Label --> <StackPanel Margin="10" Grid.Row="5"> <Label Target="{Binding ElementName=txtMail2}" > <StackPanel Orientation="Horizontal"> <Image Source="Email-icon.png" Width="25" Height="25" /> <AccessText Text="M_ail:" /> </StackPanel> </Label> <TextBox Name="txtMail2" /> </StackPanel> <!--Example - 8 Format a WPF Label using background and Gradient --> <Label Grid.Row="6"> <Label.Background> <LinearGradientBrush StartPoint="0,0" EndPoint="1,1"> <GradientStop Color="Pink" Offset="0.1" /> <GradientStop Color="Blue" Offset="0.25" /> <GradientStop Color="Green" Offset="0.75" /> <GradientStop Color="Red" Offset="1.0" /> </LinearGradientBrush> </Label.Background> <Label.Foreground> <LinearGradientBrush StartPoint="0,0" EndPoint="1,1"> <GradientStop Color="Orange" Offset="0.25" /> <GradientStop Color="Green" Offset="1.0" /> </LinearGradientBrush> </Label.Foreground> </Label> </Grid> </Window>
Basic controls:
The Label control, in its most simple form, will look very much like the TextBlock which we used in another article. You will quickly notice though that instead of a Text property, the Label has a Content property. The reason for that is that the Label can host any kind of control directly inside of it, instead of just text. This content can be a string as well though, as you will see in this first and very basic example:
<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>
Another thing you might notice is the fact that the Label, by default, has a bit of padding, allowing the text to be rendered a few pixels away from the top, left corner. This is not the case for the TextBlock control, where you will have to specify it manually.
In a simple case like this, where the content is simply a string, the Label will actually create a TextBlock internally and show your string in that.
The Label control vs. the TextBlock control
So why use a Label at all then? Well, there are a few important differences between the Label and the TextBlock. The TextBlock only allows you to render a text string, while the Label also allows you to:
- 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 an 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:
-
Catalan
-
Chinese
-
Czech
-
Danish
-
Dutch
-
French
-
German
-
Hindi
-
Hungarian
-
Italian
-
Japanese
-
Korean
-
Polish
-
Portuguese
-
Romanian
-
Russian
-
Slovak
-
Spanish
-
Ukrainian
-
Vietnamese
Is your preferred language not on the list? Click here to help us translate this article into your language!
This article demonstrates how to create and use a Label control in WPF using XAML and C#.
Creating a WPF Label
The Label element represents a WPF Label control in XAML.
- < Label />
The Width and Height attributes of the Label element represent the width and the height of a Label. The Content property of the Label element sets the text of a Label. The Name attribute represents the name of the control, which is a unique identifier of a control.
The code snippet in Listing 1 creates a Label control and sets the name, height, width, and content of a Label control. The code also sets the font format for the text.
- <Label Name=«Label1»
- Content=«Hello! I am Label Control»
- Width=«200» Height=«40»
- Canvas.Left=«10» Canvas.Top=«10»
- FontSize=«14» FontFamily=«Georgia»
- FontWeight=«Bold»/>
Listing 1
The output looks like Figure 1.
Figure 1
The Background and Foreground properties set the background and foreground colors of the Label control. The code snippet in Listing 2 sets the background, foreground, and alignment of a Label control.
- <Label Name=«Label1» Content=«Hello! I am Label Control» Width=«200» Height=«30» Canvas.Left=«10» Canvas.Top=«10» FontSize=«14» FontFamily=«Georgia» FontWeight=«Bold» Background=«Black» Foreground=«Orange» VerticalAlignment=«Center» HorizontalAlignment=«Center» />
Listing 2
The new output looks like Figure 2.
Figure 2
Adding Contents to a WPF Label
The Content property of the Label control allows you to set any other controls as the content of a Label control. The code snippet in Listing 3 adds some ellipse controls to a Label control.
- <Label Canvas.Left=«10» Canvas.Top=«50»>
- <StackPanel Orientation=«Horizontal»>
- <Ellipse Width=«100» Height=«100» Fill=«Red» />
- <Ellipse Width=«80» Height=«80» Fill=«Orange» />
- <Ellipse Width=«60» Height=«60» Fill=«Yellow» />
- <Ellipse Width=«40» Height=«40» Fill=«Green» />
- <Ellipse Width=«20» Height=«20» Fill=«Blue» />
- <Ellipse Width=«15» Height=«15» Fill=«Indigo» />
- <Ellipse Width=«10» Height=«10» Fill=«Violet» />
- </StackPanel>
- </Label>
Listing 3
Listing 3 generates an output that looks like Figure 3.
Figure 3
Formatting a WPF Label
The BorderBrush property of the Label sets a brush to draw the border of a Label. You may use any brush to fill the border. The following code snippet uses a linear gradient brush to draw the border with a combination of red and blue color.
- <Label.BorderBrush>
- <LinearGradientBrush StartPoint=«0,0» EndPoint=«1,1»>
- <GradientStop Color=«Blue» Offset=«0» />
- <GradientStop Color=«Red» Offset=«1.0» />
- </LinearGradientBrush>
- </Label.BorderBrush>
The Background and Foreground properties of the Label set the background and foreground colors of a Label. You may use any brush to fill the border. The following code snippet uses linear gradient brushes to draw the background and foreground of a Label.
- <Label.Background>
- <LinearGradientBrush StartPoint=«0,0» EndPoint=«1,1»>
- <GradientStop Color=«Blue» Offset=«0.1» />
- <GradientStop Color=«Orange» Offset=«0.25» />
- <GradientStop Color=«Green» Offset=«0.75» />
- <GradientStop Color=«Black» Offset=«1.0» />
- </LinearGradientBrush>
- </Label.Background>
- <Label.Foreground>
- <LinearGradientBrush StartPoint=«0,0» EndPoint=«1,1»>
- <GradientStop Color=«Orange» Offset=«0.25» />
- <GradientStop Color=«Green» Offset=«1.0» />
- </LinearGradientBrush>
- </Label.Foreground>
The new Label looks like Figure 4.
Figure 4
Setting Image as Background of a WPF Label
To set an image as background of a Label, we can set an image as the Background of the Label. The following code snippet sets the background of a Label to an image.
- <Label.Background>
- <ImageBrush ImageSource=«Garden.jpg» />
- </Label.Background>
The new output looks like Figure 5.
Figure 5
Summary
In this article, I discussed how we can create a Label control in WPF and C#. We also saw how we can format a Label by setting its border, background, and foreground properties. After that, we saw how to set an image as the background of a Label.
Label control is used for showing the text data in the WPF application. It also provides support for Access Keys.
<Label />
Content Property
Label is directly inherit from ContentControl class which provides the Content property to Label control.
In the Content property, you can set the string or host any type of child control.
<StackPanel Margin="10">
<Label Content="First Name" />
<TextBox x:Name="txtFirstName" />
<Label>
<StackPanel Orientation="Horizontal">
<Image Source="email.png" Height="15" Width="15" />
<TextBlock Text="Name" />
</StackPanel>
</Label>
<TextBox />
</StackPanel>
In the above example, I have set «First Name» as Content in the Label.
When you want to set any child control as Content to Label, whatever control you place between the starting and end brackets <Label>###</Label> is automatically set in Content property of Label.
In the 6th line of above example, I have set the StackPanel as child control and StackPanel are also contains two child controls Image and TextBlock.
Target Property
Target property of Label is used for setting the associated Control of Label which receives focus when user press the Access Key. I’ll explain AccessKey in below section.
Target property is set by the Binding Markup Extension and setting the ElementName property of Binding. ElementName takes the name of the control.
Below is the example of Target property.
<Label Content="_Name" Target="{Binding ElementName=txtName}" />
<TextBox Name="txtName" />
AccessKeys
Access keys are keyboard shortcuts to directly send focus on a control by pressing the combination of Alt + AccesssKey.
Below is the example:
<StackPanel>
<Label Content="_Name" Target="{Binding ElementName=txtName}" />
<TextBox Name="txtName" />
<Label Content="A_ge" Target="{Binding ElementName=txtAge}" />
<TextBox Name="txtAge" />
</StackPanel>
Put the underscore before the front of a character that makes the text mnemonic and set the Target binding to associated control name.
In the above example, I have put «_» before the «N» in the Name text and «_» before the «g» in the Age Label.
When I press Alt + N, the txtName textbox control got focus and when I press the Alt + g the txtAge textbox control got focus.
Label Text Wrapping
WPF Label by default does not provide text wrapping feature. But you can use AccessText control as child control of Label for getting the benefits of TextWrapping feature.
<Label Width="70">
<AccessText TextWrapping="Wrap" Text="Please provide your _First Name">
</AccessText>
</Label>
Change the TextColor
You can change the text color of Label by using the Foreground property. Below is the example:
<Label Foreground="Red" Content="Hello World" />
<Label Content="Hello USA">
<Label.Foreground>
<LinearGradientBrush StartPoint="0,1" EndPoint="1,0">
<GradientStop Color="Red" Offset="0.1" />
<GradientStop Color="Yellow" Offset="0.7" />
<GradientStop Color="DarkBlue" Offset="0.9" />
</LinearGradientBrush>
</Label.Foreground>
</Label>
Label Background Property
Label background property is used for setting the back color of Label.
Below is the example:
<Label Content="Hello World" Background="Red" Foreground="Yellow" />
You can also set Gradient color brush to background.
<Label Content="Hello World!!!" Margin="15" FontSize="28" Foreground="Yellow" Height="100">
<Label.Background>
<RadialGradientBrush Center="0.5,0.5">
<GradientStop Offset="0.0" Color="Yellow" />
<GradientStop Offset="1.0" Color="Red" />
</RadialGradientBrush>
</Label.Background>
</Label>
Background Image
Set the ImageBrush to Background property of Label and set the ImageSource property of ImageBrush to the source image like shown below:
<Label Content="Hello World!!!" Foreground="Green" Height="200" Padding="130,70,0,0" FontSize="40">
<Label.Background>
<ImageBrush ImageSource="nature-wallpaper.jpg" />
</Label.Background>
</Label>
Text Alignment
Label provides 4 properties for setting the alignment.
- HorizontalAlignment
- VerticalAlignment
- HorizontalContentAlignment
- VerticalContentAlignment
HorizontalAlignment and VerticalAlignment set the horizontally or vertically position of the control within its parent control.
For example, if your parent control is 500px wide and your control is 100px wide and you want to set your control in the middle of parent control, then you set the HorizontalAlignment of control to Center.
VerticalAlignment: If your parent control has 100px height and your control has 100px height and you want to set your control in the bottom of parent control, then you set the VerticalAlignment of control to Bottom.
Possible values for HorizontalAlignment are:
- Center
- Left
- Right
- Stretch
Possible values for VerticalAlignment are:
- Bottom
- Center
- Stretch
- Top
<Grid Width="200" Height="200" Background="LemonChiffon">
<Label Content="Hello" HorizontalAlignment="Right" VerticalAlignment="Bottom" />
</Grid>
HorizontalContentAlignment and VerticalContentAlignment determines the control Content position within the control.
Possible values for HorizontalContentAlignment are:
- Center
- Left
- Right
- Stretch
Possible values for VerticalContentAlignment are:
- Bottom
- Center
- Stretch
- Top
<Label Content="Hello World!!!" Foreground="Yellow" Height="200" FontSize="40" HorizontalContentAlignment="Center" VerticalContentAlignment="Bottom">
<Label.Background>
<ImageBrush ImageSource="nature-wallpaper.jpg" />
</Label.Background>
</Label>
In the above example, I have set HorizontalContentAlignment to ‘Center’ and VerticalContentAlignment to ‘Bottom’. These settings change the Content position to the horizontally center and vertically bottom within the Label.
Difference between TextBlock and Label
TextBlock and Label are almost looks same but there are some major differences in them:
- TextBlock is used for multiline text but label is used for single line text.
- Label is directly inherit from ContentControl whereas TextBlock control inherits from FrameworkElement.
- TextBlock provides the Text property for display any data in string format but Label provides Content property for display any type of control as child.
- Label provides support for AccessKeys for directly send the focus on asscoiated control but TextBlock does not support AccessKeys.
- Label provides a Border control around its contents but TextBlock does not. Label has BorderBrush and BorderThickness properties for customizing the border properties.
- When you disable the Label, Label forground color has changed to Gray but TextBlock does not change foreground color when disabled.
- TextBlock provides support TextWrapping feature but Label does not.
As far as I remember, in most cases classes like TextBlock
, TextBox
and many others take the text color from the TextElement.Foreground
property. The property value is inherited throughout the visual tree, i.e. you may set it on the root element and have most of the text change its color. For example:
<Grid TextElement.Foreground="Red">
<TextBlock Text="test"/>
</Grid>
In fact, the same is true even for labels: the setter in their default style simply sets the TextElement.Foreground
to one of the system colors.
However, this is true only for the default state of controls. Altered states, like highlighting, are not inherited, but rather taken from the system colors, as Rachel has written.
UPDATE
The same is true for FontSize
and FontFamily
. They are properties of the TextElement
class that have attached property usage. They inherit their values. Once you set a value on a visual tree item, all its children will get the same value. Unless they override it either by an explicit property assignment, or by style and so on.
Once again, text color font size and font family are governed by the value of TextElement.Foreground
, TextElement.FontSize
and TextElement.FontFamily
attached dependency properties on a specific visual element.
Some controls, like Label
explicitly set their Foreground
to some brush. It happens so that the brush is one of the SystemColors
. But it doesn’t have to be true for all controls. Others (TextBlock
, TextBox
, etc.) don’t override the property value and just use some default settings evaluated on startup. The same happens to FontSize
and FontFamily
. You do not need to set them wherever in order for them to work. That’s how WPF works.
Supposedly, the values depend on the system theme. I believe they are evaluated during the app startup. Perhaps they are configurable.
UPDATE 2
Answers to your new questions:
How does a TextBlock get its default color, if the client app doesn’t provide any style, either programmatically or through xaml?
It takes it from the inherited value of the TextElement.Foreground
attached dependency property. By default it is inherited from the root visual element, which in turn is simply set to the default value of the dependency property (Brushes.Black
). See also
How does a Label get its default color?
It takes it from the value of the TextElement.Foreground
attached dependency property. Since its default style sets it to the {DynamicResource {x:Static SystemColors.ControlTextBrushKey}
, it gets bound to the system color.
How does a TextBlock get its default font size and font family, if the client app doesn’t provide any style, either programmatically or through xaml?
The same as for its text color. MSDN says that for the default value of the font size is SystemFonts.MessageFontSize which depends on system settings. Font family is determined in similar way from SystemFonts.MessageFontFamily.
Both these default values are passed to the FrameworkPropertyMetadata
constructor upon dependency property registration in the TextElement
static constructor.
Going deeper: SystemFonts.MessageFontFamily
and SystemFonts.MessageFontSize
wrap internal SystemParameters.NonClientMetrics
which in turn are retrieved from the WIN32 native SystemParametersInfo
http://msdn.microsoft.com/en-us/library/ms724947. Thus the WPF is tightly integrated with all Windows UI stuff like themes, fonts, etc.
How does a Label get its default font size and font family?
The same as for TextBlock
. Label
derives from ContentControl
which in turn derives from Control
. Control
class adds itself as an owner of the TextElement.FontFamily
and TextElement.FontSize
properties with the same default values.
See also:
Property Value Inheritance
UPDATE 3
You should understand the main idea: the values are inherited. It means they might be inherited from anywhere, from any control. You can tell exactly which one it is inherited from only for a certain logical tree structure. You change it a bit — and the colors change. Someone sets a property’s value explicitly — and all children will inherit the value. Therefore your questions make little practival sense. But they are still interesting from the perspective of undestanding the WPF.
Overriding default values
Although you cannot change the values of the SystemFonts
properties (they are read-only), you don’t have to. To change the font size and family for the whole window, simply assign the desired values to the TextElement
attached properties on the Window
:
<Window TextElement.FontSize="20" TextElement.FontFamily="Century Gothic">
..
</Window>
and all controls that do not explicitly override the inheritance will receive the settings. For those that do override — you’ll have to override their default styles or even throw them away if they hard-code the values.
The same approach works for TextElement.Foreground
(and Background
and so on).