tags:

views:

1696

answers:

6

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.

A: 

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.

Drew Noakes
A: 

How about:

TextBlock textBlock = new TextBlock();
textBlock.Inlines.Add("Two");
textBlock.Inlines.Add(new LineBreak());
textBlock.Inlines.Add("Lines");
Button button = new Button();
button.Content = textBlock;

If you're using C# 3 you can make that slightly neater:

Button button = new Button
{
    Content = new TextBlock { Inlines = { "Two", new LineBreak(), "Lines" } }
};
Jon Skeet
A: 

See my comments under the original question. The answer was that I was looking in the wrong place for the problem! It was a problem in the buttons' container, but the buttons themselves. Sorry.

Paul
@Paul: There's nothing wrong with answering your own question - the question and answer will live here and help future readers. But the correct way to do it is to post your solution as an answer, and accept that answer. Don't bury the solution in a comment and then add an answer pointing to the comment. 8-)
RichieHindle
A: 

As per RichieHindle's comment, I'm trying to become a better member of the community by posting my answer as an answer rather than a comment. :)

Turns out the "\n" works fine. My grid had a fixed size, and there is simply no visual indication in a button that there's more text available (e.g., no "..." indicating a cutoff). Once I generously expanded the size of my grid, the button text showed up in two rows.

Paul
+3  A: 

OR in XAML directly:

<Button>
   <TextBlock>Two<LineBreak/>Lines</TextBlock>  
</Button>
Sergey Malyan
A: 

Wow...That Worked Thanks... TwoLines

reddy