Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a TextBlock to a Label in C# Code WPF

Tags:

c#

wpf

xaml

In my code I am creating a new Label and formatting it and making it a child of a Stacked Panel. But inside of the Label I need to add a Text Block and I am having trouble to find out how to do this.

Using Code only I need to the WPF created by the code to work like this:

<Label Background="#000000" Foreground="#FFFFFF">
    <TextBlock TextWrapping="Wrap" Text="Text Here"/>
</Label>

But I can not figure out how to get that TextBlock inside of the Label in the code, what I thought would work isn't working because it is a Label:

 NewLabel.Children.Add(NewTextBlock);

But this works when I use it to add the NewLabel to the StackedPanel.

The whole reason I need this to work is because I need text wrapping in the Label, but can't use just the TextBlock or other Control.

like image 776
ZHolmes Avatar asked Jan 20 '26 17:01

ZHolmes


1 Answers

Just set the TextBlock as the content of the label to achieve your requirement.

Label lbl = new Label ();
TextBlock txtBlock = new TextBlock ();
txtBlock.TextWrapping = TextWrapping.Wrap;
lbl.Content = txtBlock;
like image 142
Sivasubramanian Avatar answered Jan 22 '26 08:01

Sivasubramanian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!