如何在 RichTextBox 中获取所选文本的父标签? [英] How to get the parent tag of selected text in RichTextBox?
本文介绍了如何在 RichTextBox 中获取所选文本的父标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 RichTextBox
控件中得到了 FlowDocument
:
I got that FlowDocument
in the RichTextBox
control:
<RichTextBox>
<FlowDocument>
<Paragraph>
<Span>First Line</Span>
</Paragraph>
<Paragraph>
<Span>Second Line</Span>
</Paragraph>
<Paragraph>
<Span>Third Line</Span>
</Paragraph>
</FlowDocument>
</RichTextBox>
我想引用所选文本的父 Paragraph
标记,因为我需要更改段落的 TextAlignment
属性.
I want to get reference to a parent Paragraph
tag of the selected text because I need to change the TextAlignment
property of the paragraph.
推荐答案
尝试使用下面声明的 GetParentParagraph()
方法:
Try to use the GetParentParagraph()
method declared below:
public static class TextRangeExt
{
public static Paragraph GetParentParagraph(this TextPointer position)
{
var direction = LogicalDirection.Backward;
for (; position != null; position = position.GetNextContextPosition(direction))
{
if (position.GetAdjacentElement(direction) is Paragraph para) { return para; }
}
return null;
}
}
以下代码用于测试目的.
The code below is for testing purposes.
MainWindow.xaml:
<Window ...>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<RichTextBox Name="rtb" BorderBrush="{x:Null}" Padding="5" Margin="10"
VerticalScrollBarVisibility="Auto">
<FlowDocument>
<Paragraph>
<Span>First Line</Span>
</Paragraph>
<Paragraph>
<Span>Second Line</Span>
</Paragraph>
<Paragraph>
<Span>Third Line</Span>
</Paragraph>
</FlowDocument>
</RichTextBox>
<Button Grid.Row="1" Click="Button_SearchParagraph" Margin="2" Padding="3">Search Parent Paragraph</Button>
</Grid>
</Window>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_SearchParagraph(object sender, RoutedEventArgs e)
{
var range = rtb.Selection;
if (!range.IsEmpty)
{
if (range.Start.GetParentParagraph() is Paragraph para)
rtb.CaretPosition = para.ContentStart;
}
rtb.Focus();
}
}
这篇关于如何在 RichTextBox 中获取所选文本的父标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文