在多次运行的 WPF Textblock 中,我如何将样式应用于特定样式?

In WPF Textblock with multiple runs how do i apply a style to a particular one?

如何不在整个文本块上应用样式,而只在第一个 运行(粗体)上应用样式?

我想在粗体 运行 上应用 "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;

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>