好的,要将文本包装在按钮中,您可以像这样使用 XAML:
<Button Width="200" Height="200">
<Button.Content>
<TextBlock TextWrapping="Wrap" Text="This is a long text that fits into button"/>
</Button.Content>
</Button>
为了在代码中完成此操作,您可以执行以下操作:
Button btn = new Button();
btn.Height = 200;
btn.Width = 300;
TextBlock txt = new TextBlock();
txt.TextWrapping = TextWrapping.Wrap;
txt.Text = "A huge amount of text that will fill the button";
btn.Content = txt;
ContentPanel.Children.Add(btn);
ContentPanel 是一个简单的网格。
编辑:HyperlinkButton 的修改后的帖子
为了在超链接按钮中启用文本换行,您需要编辑超链接按钮的样式。在 App.xaml 文件中像这样定义它:
<Style x:Key="HyperlinkButtonStyle" TargetType="HyperlinkButton">
<Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="FontSize" Value="{StaticResource PhoneFontSizeMedium}"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="HyperlinkButton">
<Border Background="Transparent">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver"/>
<VisualState x:Name="Pressed">
<Storyboard>
<DoubleAnimation Duration="0" To="0.5" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="TextElement"/>
</Storyboard>
</VisualState>
<VisualState x:Name="Disabled">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="TextElement">
<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border Background="{TemplateBinding Background}" Margin="{StaticResource PhoneHorizontalMargin}" Padding="{TemplateBinding Padding}">
<TextBlock x:Name="TextElement" TextWrapping="Wrap" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Text="{TemplateBinding Content}" TextDecorations="Underline" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
重要的变化是 TextBlock 现在包含设置为“Wrap”的 TextWrapping 属性。
然后像往常一样使用按钮,只是不要忘记设置样式:
var btn = new HyperlinkButton();
btn.Height = 200;
btn.Width = 300;
btn.NavigateUri = new Uri("http://bing.com", UriKind.Absolute);
btn.TargetName = "_blank";
btn.Style = Application.Current.Resources["HyperlinkButtonStyle"] as Style;
btn.Content = "This is a huge amount of text that will be in the hyperlink button";
ContentPanel.Children.Add(btn);