我如何在WPF按钮上仅使用C#实现多行文本?我看到过在XAML中使用<LineBreak/>
的示例,但我的按钮完全是通过C#编程创建的。按钮上的数字和标签与域模型中的值对应,因此我不认为可以使用XAML来指定它们。
我尝试了下面这种朴素的方法,但它不起作用。
Button b = new Button();
b.Content = "Two\nLines";
或者b.Content = "Two\r\nLines";
无论哪种情况,我只看到文本的第一行(“Two”)。
我如何在WPF按钮上仅使用C#实现多行文本?我看到过在XAML中使用<LineBreak/>
的示例,但我的按钮完全是通过C#编程创建的。按钮上的数字和标签与域模型中的值对应,因此我不认为可以使用XAML来指定它们。
我尝试了下面这种朴素的方法,但它不起作用。
Button b = new Button();
b.Content = "Two\nLines";
或者b.Content = "Two\r\nLines";
无论哪种情况,我只看到文本的第一行(“Two”)。
或者在XAML中直接使用:
<Button>
<TextBlock>Two<LineBreak/>Lines</TextBlock>
</Button>
我更喜欢这种方式:
<Button Width="100">
<TextBlock TextWrapping="Wrap">This is a fairly long button label</TextBlock>
</Button>
对我有效。


来引入换行符,例如:<Button Content="Row 1 Text 
 Row 2 Text"/>
<Button Content="__
-"/>
双下划线。 - Luiey有多种方法可以通过XAML实现这一点:
<Button>
<TextBlock TextAlignment="Center">Line 1<LineBreak/>Line 2</TextBlock>
</Button>
这种方法很简单,但没有办法轻松控制文本的对齐方式:
<Button Content="Line 1 
 Line 2"/>
一旦按钮大小小于文本块大小,它将自动将内容拆分为两行或更多行。
<Button>
<TextBlock TextWrapping="Wrap" HorizontalAlignment="Center">Line 1 Line 2</TextBlock>
</Button>
你可以在按钮中使用 StackPanel,并将每行作为 TextBlock 添加进去:
<Button>
<StackPanel>
<TextBlock Text="Line1" HorizontalAlignment="Center"/>
<TextBlock Text="Line2" HorizontalAlignment="Center"/>
</StackPanel>
</Button>
在你的按钮中使用网格布局:<Button>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Text="Line1" HorizontalAlignment="Center"/>
<TextBlock Text="Line2" HorizontalAlignment="Center"/>
</Grid>
</Button>
我相信还有很多,这个列表基本上是按最喜欢到最不喜欢的顺序排列的。这是我们这里的做法,它可以轻松居中。
<Button Height="40" Width="75">
<StackPanel>
<TextBlock Text="Line1" HorizontalAlignment="Center"/>
<TextBlock Text="Line2" HorizontalAlignment="Center"/>
</StackPanel>
</Button>
你尝试过这个吗?
b.Content = new TextBlock {
Text = "Two\nLines",
TextWrapping = TextWrapping.Wrap };
TextBlock textBlock = new TextBlock();
textBlock.Inlines.Add("Two");
textBlock.Inlines.Add(new LineBreak());
textBlock.Inlines.Add("Lines");
Button button = new Button();
button.Content = textBlock;
如果你正在使用C# 3,你可以使代码更简洁:
Button button = new Button
{
Content = new TextBlock { Inlines = { "Two", new LineBreak(), "Lines" } }
};
我遇到了同样的问题。
我尝试过:
- button.content = "Line1\nLine2"(没有起作用,可能是我做错了什么);
- 用新标签替换按钮文本(无法让文本居中对齐);
- 用文本块替换按钮文本(我认为这可以让文本居中对齐,但不能自动换行);
我看到有答案提到使用stackpanels或grids。
我看到有答案说不要使用Textbox。
\n
可以工作,但我认为这不是正确的方法。在我看来,你只是强制控件做你想要的事情,如果你需要更改文本,你将不得不检查文本是否正确换行或\n
是否需要放在另一个位置。Focusable = false
可以防止用户选择文本,即使他不能编辑它,我也不希望他选择它(个人喜好)。这将使文本框的行为类似于标签,但具有让您居中对齐文本的优势。
尝试以下代码:
<Button Command="{Binding DeliveryDateCommand}" x:Name="cntlbtnf5" Background="White" BorderBrush="#FFABADB3" Grid.Column="4">
<Border BorderBrush="{x:Null}" Height="Auto">
<TextBlock Text="Ctrl + F5 Delivery BillDate" TextWrapping="Wrap" Width="110" TextAlignment="Center" Height="44" />
</Border>
</Button>