wpf 如何在标签中添加换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15975284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a line break in a label
提问by DDR
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.NewLinebut this is not working in WPF application
A B C 我已经在 WinForms c# 中完成了这个,Environment.NewLine但这在 WPF 应用程序中不起作用
Can some one tell me how can i add line break in label?
有人可以告诉我如何在标签中添加换行符吗?
Am doing this from code behind and not XAML
我是从背后的代码而不是这样做的 XAML
回答by Isak Savo
If you're fine with using TextBlock instead of Label(you should be!), then you can do it like this:
如果您可以使用TextBlock 而不是 Label(您应该这样做!),那么您可以这样做:
<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"));
回答by Singleton
I don't think that Environment.NewLineis 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
我不认为这Environment.NewLine在你的情况下不起作用。检查 XAML 中标签的高度。当您添加换行符时,它会增加标签中的内容,如果高度不够,则您看不到。我认为您正面临这个问题,否则我认为没有任何问题Environment.NewLine:) 尝试添加高度并告诉我
回答by A Aiston
Either set your max width and let the layout mechanism work out where to put your carriage return or put some \n in there
要么设置你的最大宽度,让布局机制计算在哪里放回车或放一些 \n 在那里
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
在上面的代码中, pan 只是一个堆栈面板控件,当然,您将添加到包含您的标签的任何控件中

