我是 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));
}
答案 0 :(得分:0)
您可以在 Document
的 RichTextBox
中添加不同类型的 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));
}