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.
I had the same issue.
I tried:
- button.content = "Line1\nLine2" (didn't work, maybe I did something wrong);
- replace button text with a new label (doesn't let you center align the text);
- replace button text with a text block (I think this lets you center align the text but doesn't wrap it);
I've seen answers mentioning the use of stackpanels or grids.
I've seen answers saying not to use a Textbox.
Even though the OP says that the
\n
works, I don't think that that is the way to go, in my opinion you're just brute forcing the control to do what you want and if at any point you need to change the text you will have to go and check if the text is correctly wrapped or if the\n
needs to be in another position.What I found to be the best way to go (to me) is to replace the button content with a text box (you can just drag and drop, no need to mess with XAML) and set the following properties as stated: IsReadOnly = true;
Focusable = false (optional);
I think
Focusable = false
prevents the user from selecting the text, even though he can't edit it, I don't want him to even select it (personal taste).This will make the text box behave similar to a label but with the advantage that lets you center align the text.
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.
How about:
If you're using C# 3 you can make that slightly neater:
There are several ways to do this via XAML:
This method is simple but there is no way to easily control the alignment of the text:
Once the Buttons size is smaller than the TextBlocks size it will simply split the content into two lines or more automatically
This is how we do it here it allows for easy centering as well
Try below code: