繁体   English   中英

将段落或文本框附加到 RichTextBox

[英]Appending a Paragraph or Textbox to a RichTextBox

我是 C# 的新手,但在任何地方都找不到有关如何以编程方式将段落或文本框 append 到 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));
}

编辑添加图片以便更好地理解。 一张图片是当你在没有选择文本的情况下按下点击事件,另一张是如果你做 select 文本然后点击事件不选择文本

粘贴到盒子里

您可以向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