【发布时间】:2015-02-04 21:33:09
【问题描述】:
我想知道如何在 WPF 按钮中垂直显示文本。我有一个高矩形按钮,宽度 = 38,高度 = 90。我希望按钮将文本显示为
乙
你
是的
或
S
电子
大号
谁能告诉我如何在 WPF 中实现这一点。
谢谢
【问题讨论】:
-
你做了哪些努力?
我想知道如何在 WPF 按钮中垂直显示文本。我有一个高矩形按钮,宽度 = 38,高度 = 90。我希望按钮将文本显示为
乙
你
是的
或
S
电子
大号
谁能告诉我如何在 WPF 中实现这一点。
谢谢
【问题讨论】:
您可以简单地使用 ItemsControl,它会在其中创建一个元素列表,使它们看起来是垂直的。
<Button>
<ItemsControl ItemsSource="BUY" />
</Button>
您可以在this question..上找到有关执行此类操作的更多信息..
【讨论】:
IEnumerable。 +1 表示大胆,尽管它可以使用一些解释。
也许这个答案对你有帮助。 您基本上需要一种样式来包装添加到按钮的文本。
看看这个答案: WPF button textwrap style
【讨论】:
ItemsControl 的答案听起来很完美,但如果您不想这样做,您可以创建一个转换器,在文本的每个字符之间添加一个“\n”。
页面的 XAML:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DilbertDownloader" x:Class="DilbertDownloader.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:TextVerticalConverter x:Key="TextVerticalConverter"/>
</Window.Resources>
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Grid>
<Button Content="{Binding ButtonText, Converter={StaticResource TextVerticalConverter}}" HorizontalAlignment="Left" Margin="270,156,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
</Window>
转换器的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DilbertDownloader
{
public class TextVerticalConverter : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (!(value is string)) return value;
var converted = "";
foreach (var character in (string)value)
{
//If the character is a space, add another new line
//so we get a vertical 'space'
if (character == ' ') {
converted += '\n';
continue;
}
//If there's a character before this one, add a newline before our
//current character
if (!string.IsNullOrEmpty(converted))
converted += "\n";
converted += character;
}
return converted;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//Not really worried about this at the moment
throw new NotImplementedException();
}
}
}
以及 ViewModel 的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DilbertDownloader
{
public class ViewModel
{
public string ButtonText { get; set; }
public ViewModel()
{
ButtonText = "BUY";
}
}
}
希望对你有帮助
【讨论】:
使用换行符和文字换行符
<Button Width="38" Height="90" Content="B
u
y"/>
<Button Width="38" Height="90">
<TextBlock>
<Run Text="S"/>
<LineBreak/>
<Run Text="E"/>
<LineBreak/>
<Run Text="L"/>
<LineBreak/>
<Run Text="L"/>
<LineBreak/>
</TextBlock>
</Button>
为文本块设置宽度和文本换行
<Button Width="38" Height="90">
<TextBlock Text="Buy" Width="8" TextWrapping="Wrap"></TextBlock>
</Button>
【讨论】: