如何在整个文本块中应用样式,但仅在第一次运行时使用样式(粗体)?
我想在粗体运行中应用样式“XXXFontName-Bold”,在其余部分应用样式“XXXFontName-Thin”。
// add button
Button btn = new Button();
TextBlock contextText = new TextBlock();
contextText.Inlines.Add(new Bold(new Run(label.Substring(0,1))));
contextText.Inlines.Add(new Style()); <===== OBVIOUS ERROR HERE
contextText.Inlines.Add(label.Substring(1));
contextText.FontSize = 25;
contextText.Style = FindResource("XXXFontName-Thin") as Style;
btn.Content = contextText;
答案 0 :(得分:2)
3个示例样式,在XAML中使用样式和换行设置运行的示例,以及如何在按钮后面的代码中设置它们
您的代码背后:
public MainWindow()
{
InitializeComponent();
Button btn = new Button();
TextBlock contextText = new TextBlock();
var newRun = new Run("BoldGreenRunStyle");
newRun.Style = FindResource("BoldGreenRunStyle") as Style;
contextText.Inlines.Add(newRun);
newRun = new Run("ItalicRedRunStyle");
newRun.Style = FindResource("ItalicRedRunStyle") as Style;
contextText.Inlines.Add(newRun);
newRun = new Run("ThinPurpleRunStyle");
newRun.Style = FindResource("ThinPurpleRunStyle") as Style;
contextText.Inlines.Add(newRun);
btn.Content = contextText;
Container.Children.Add(btn);
}
你的XAML
<Window.Resources>
<Style TargetType="Run" x:Key="BoldGreenRunStyle">
<Setter Property="Foreground" Value="Green"></Setter>
<Setter Property="FontWeight" Value="Bold"></Setter>
</Style>
<Style TargetType="Run" x:Key="ItalicRedRunStyle">
<Setter Property="Foreground" Value="Red"></Setter>
<Setter Property="FontWeight" Value="Normal"></Setter>
<Setter Property="FontStyle" Value="Italic"></Setter>
</Style>
<Style TargetType="Run" x:Key="ThinPurpleRunStyle">
<Setter Property="Foreground" Value="Purple"></Setter>
<Setter Property="FontWeight" Value="Thin"></Setter>
</Style>
</Window.Resources>
<StackPanel x:Name="Container">
<Label Content="From XAML"></Label>
<TextBlock>
<TextBlock.Inlines>
<Run Style="{StaticResource BoldGreenRunStyle}">BoldGreenRunStyle</Run>
<LineBreak/>
<Run Style="{StaticResource ItalicRedRunStyle}">ItalicRedRunStyle</Run>
<LineBreak/>
<Run Style="{StaticResource ThinPurpleRunStyle}">ThinPurpleRunStyle</Run>
<LineBreak/>
</TextBlock.Inlines>
</TextBlock>
</StackPanel>