简体   繁体   English

将段落或文本框附加到 RichTextBox

[英]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.我是 C# 的新手,但在任何地方都找不到有关如何以编程方式将段落或文本框 append 到 RichTextBox 的详细信息,如果可能的话。 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: 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: 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一张图片是当你在没有选择文本的情况下按下点击事件,另一张是如果你做 select 文本然后点击事件不选择文本

粘贴到盒子里

You can add different kind of blocks to the Document of the RichTextBox :您可以向RichTextBoxDocument添加不同类型的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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