在多次运行的WPF文本块中,如何将样式应用于特定样式

本文关键字:样式 应用于 运行 WPF 文本 | 更新日期: 2023-09-27 18:20:01

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

我想在粗体Run上应用样式"XXXFontName Bold",在其余部分应用样式"XXXXFontName 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;

在多次运行的WPF文本块中,如何将样式应用于特定样式

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>