【发布时间】:2021-08-14 05:21:10
【问题描述】:
我是 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));
}
【问题讨论】:
-
CodeBlock_Click()处理程序的内容不够清晰。您想将背景颜色、字体属性应用于所有文档还是仅应用于当前插入段落的文本? -
如果当前插入的段落,则只到文本。我希望得到,如果您选择文本,它会将内容框在一个矩形中文字
-
我是否理解正确,当没有选择文本时,
CodeBlock_Click()应该在当前插入符号位置插入一个带有 '// 代码占位符' 文本的新段落?如果是,如果插入符号位于某个段落内会发生什么?新创建的段落(包含 '// 代码占位符' 文本)是否会在插入符号位置拆分当前段落? -
嗯,好点。我猜插入符号将在框外,并且在单击框时。 '// 代码占位符' 将消失
标签: c# xml wpf richtextbox