4

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

Dilshod
  • 3,189
  • 3
  • 36
  • 67
DDR
  • 1,272
  • 1
  • 12
  • 19

3 Answers3

11

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"));
Community
  • 1
  • 1
Isak Savo
  • 34,957
  • 11
  • 60
  • 92
7

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

Singleton
  • 3,701
  • 3
  • 24
  • 37
3

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

A Aiston
  • 717
  • 5
  • 12