Multiline Text in a WPF Button

2020-05-18 04:10发布

How do I get multi-line text on a WPF Button using only C#? I have seen examples of using <LineBreak/> in XAML, but my buttons are created completely programmatically in C#. The number and labels on the buttons correspond to values in the domain model, so I don't think I can use XAML to specify this.

I have tried the naive approach below, but it does not work.

Button b = new Button();
b.Content = "Two\nLines";

or

b.Content = "Two\r\nLines";

In either case, all i see is the first line ("Two") of the text.

标签: c# wpf multiline
10条回答
对你真心纯属浪费
2楼-- · 2020-05-18 05:04

Answer is very simple. Just use &#xa; to introduce line-break, i.e.:

<Button Content="Row 1 Text &#xa; Row 2 Text"/>
查看更多
萌系小妹纸
3楼-- · 2020-05-18 05:04

Have you tried this?

b.Content = new TextBlock { 
    Text = "Two\lLines", 
    TextWrapping = TextWrapping.Wrap };

If that doesn't work, then you could try adding a StackPanel as a child and adding two TextBlock elements to that.

查看更多
放荡不羁爱自由
4楼-- · 2020-05-18 05:13

OR in XAML directly:

<Button>
   <TextBlock>Two<LineBreak/>Lines</TextBlock>  
</Button>
查看更多
等我变得足够好
5楼-- · 2020-05-18 05:13

I prefer this way:

<Button Width="100">
  <TextBlock TextWrapping="Wrap">This is a fairly long button label</TextBlock>
</Button>

it worked for me.

查看更多
登录 后发表回答