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

use*_*910 2 c# wpf styling

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

我想在 Bold Run 上应用样式“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;
Run Code Online (Sandbox Code Playgroud)

kir*_*tab 5

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);
}
Run Code Online (Sandbox Code Playgroud)

你的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>
Run Code Online (Sandbox Code Playgroud)