DDR
DDR

Reputation: 1322

How to add a line break in a label

How to add a line break in a label. I have a label in which i m adding a text which will result in this display

A B C i have done this in WinForms c# with Environment.NewLine but this is not working in WPF application

Can some one tell me how can i add line break in label?

Am doing this from code behind and not XAML

Upvotes: 4

Views: 9813

Answers (3)

Isak Savo
Isak Savo

Reputation: 35884

If you're fine with using TextBlock instead of Label (you should be!), then you can do it like this:

<TextBlock>
    <Run Text="First Line"/>
    <LineBreak/>
    <Run Text="Second Line"/>
</TextBlock>

You can do this from code behind as well (not sure why you would want to though):

tb.Inlines.Add(new Run("First Line"));
tb.Inlines.Add(new LineBreak());
tb.Inlines.Add(new Run("Second Line"));

Upvotes: 11

Singleton
Singleton

Reputation: 3679

I don't think that Environment.NewLine is not working in your case. Check the height of your label in XAML. When you add a Line Break then it increases the content in label and if height is not enough then you cant see that. I think you are facing this problem other wise i don't see any problem with Environment.NewLine :) Try adding height and tell me

Upvotes: 7

A Aiston
A Aiston

Reputation: 717

Either set your max width and let the layout mechanism work out where to put your carriage return or put some \n in there

    TextBlock tb = new TextBlock();
        tb.Text = "This is a line with a carriage return";
        tb.MaxWidth = 100;
        tb.TextWrapping = TextWrapping.Wrap;


        pan.Children.Add(tb);

in the code above, pan is just a stack panel control, you'll be adding to whatever control houses your label of course

Upvotes: 3

Related Questions