如何解决将段落或文本框附加到 RichTextBox
我是 C# 的新手,但在任何地方都找不到有关如何以编程方式将段落或文本框附加到 RichTextBox 的详细信息(如果可能的话)。 我的最终目标是在带有预制属性的插入符号中插入一个预制的“代码块”。 这是我目前所拥有的
XML:
<ToolBar Margin="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"/>
</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));
}
编辑添加了图片以便更好地理解。一张图片是当您按下单击事件而不选择文本时,另一张是您选择文本然后单击事件
解决方法
您可以在 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));
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。