简体   繁体   中英

Appending a Paragraph or Textbox to a RichTextBox

Im new to C# but cannot find details anywhere on how to append a Paragraph or Textbox to a RichTextBox programmatically, if it is possible at all. My end goal is to have a premade "Code Block" insert at the caret with premade properties. This is what i have so far

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));
}

Edited added pictures for better under standing. One picture is when you press the click event without selecting text and the other is if you do select text and then click event不选择文本

粘贴到盒子里

You can add different kind of blocks to the Document of the RichTextBox :

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM