Reputation: 2372
How do I apply a style not on the whole textblock, but only on the first run (the Bold)?
I want to apply the style "XXXFontName-Bold" on the Bold Run AND the style "XXXFontName-Thin" on the rest.
// 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;
Upvotes: 2
Views: 5338
Reputation: 1306
3 Example Styles, Example to set runs in XAML with the styles and new lines and also how to set them in the code behind in your button
Your code behind:
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);
}
Your 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>
Upvotes: 5