将段落或文本框附加到 RichTextBox

时间:2021-05-25 23:45:11

标签: c# xml wpf richtextbox

我是 C# 的新手,但在任何地方都找不到有关如何以编程方式将段落或文本框附加到 RichTextBox 的详细信息(如果可能的话)。 我的最终目标是在带有预制属性的插入符号中插入一个预制的“代码块”。 这是我目前所拥有的

XML:

<ToolBar Margin="0,0,0,-40">
    <Menu VerticalAlignment="Center" Background="Transparent">
        <MenuItem Header="+ Insert">
            <MenuItem Header="Speech" Click="speechButton_Click"/>
            <MenuItem Header="Code Block" Click="CodeBlock_Click"/>
        </MenuItem>


 <Grid>
    <Grid>
        <!--<TextBox x:Name="titleTextBox" 
                 Margin="10"
                 Text="{Binding Path=SelectedNote.Title, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>-->
        <RichTextBox x:Name="contentRichTextBox"
                 TextChanged="contentRichTextBox_TextChanged"
                 SelectionChanged="contentRichTextBox_SelectionChanged" Margin="0, 0, 0, 0"/>
    </Grid>
</Grid>

CS:

private void CodeBlock_Click(object sender, RoutedEventArgs e)
{
    var textRange = new TextRange(contentRichTextBox.Selection.Start, contentRichTextBox.Selection.End);
    textRange.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Snow);
    textRange.ApplyPropertyValue(TextElement.FontFamilyProperty, new FontFamily("Consolas"));
    textRange.ApplyPropertyValue(TextElement.FontSizeProperty, (double)fontSizeComboBox.SelectedItem);
    textRange.ApplyPropertyValue(Block.MarginProperty, new Thickness(0));
}

编辑添加了图片以便更好地理解。一张图片是当您按下单击事件而不选择文本时,另一张是您选择文本然后单击事件 Without selecting text

Pasting into the box

1 个答案:

答案 0 :(得分:0)

您可以在 DocumentRichTextBox 中添加不同类型的 blocks

private void CodeBlock_Click(object sender, RoutedEventArgs e)
{
    contentRichTextBox.Document.Blocks.Add(new Paragraph(new Run("text")));

    var textRange = new TextRange(contentRichTextBox.Document.ContentStart, contentRichTextBox.Document.ContentEnd);
    textRange.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Snow);
    textRange.ApplyPropertyValue(TextElement.FontFamilyProperty, new FontFamily("Consolas"));
    textRange.ApplyPropertyValue(TextElement.FontSizeProperty, (double)fontSizeComboBox.SelectedItem);
    textRange.ApplyPropertyValue(Block.MarginProperty, new Thickness(0));
}