我想在 RichTextBlock 中突出显示选定的文本,但是当我在选择文本后单击“btnHighlight”按钮时,突出显示的文本与选择不匹配(可能是因为超链接,但你怎么能解决它?)。我哪里错了?
MainPage.xaml:
<Grid>
<RichTextBlock Name="Rtb" Margin="0,150,0,150" Width="300">
<Paragraph TextIndent="0">
<Hyperlink UnderlineStyle="None" CharacterSpacing="0">
<Run Text="1" FontSize="20" FontWeight="Bold"/>
</Hyperlink>
<Run Text="Text a" FontSize="20"/>
<Hyperlink UnderlineStyle="None">
<Run Text="2" FontSize="20" FontWeight="Bold"/>
</Hyperlink>
<Run Text="Text b" FontSize="20"/>
<Hyperlink UnderlineStyle="None">
<Run Text="3" FontSize="20" FontWeight="Bold"/>
</Hyperlink>
<Run Text="Text c" FontSize="20"/>
<Hyperlink UnderlineStyle="None">
<Run Text="4" FontSize="20" FontWeight="Bold"/>
</Hyperlink>
<Run Text="Text d" FontSize="20"/>
<Hyperlink UnderlineStyle="None">
<Run Text="5" FontSize="20" FontWeight="Bold"/>
</Hyperlink>
<Run Text="Text e" FontSize="20"/>
<Hyperlink UnderlineStyle="None">
<Run Text="6" FontSize="20" FontWeight="Bold"/>
</Hyperlink>
<Run Text="Text f" FontSize="20"/>
<Hyperlink UnderlineStyle="None">
<Run Text="7" FontSize="20" FontWeight="Bold"/>
</Hyperlink>
<Run Text="Text g" FontSize="20"/>
<Hyperlink UnderlineStyle="None">
<Run Text="8" FontSize="20" FontWeight="Bold"/>
</Hyperlink>
<Run Text="Text h" FontSize="20"/>
<Hyperlink UnderlineStyle="None">
<Run Text="9" FontSize="20" FontWeight="Bold"/>
</Hyperlink>
<Run Text="Text i" FontSize="20"/>
<Hyperlink UnderlineStyle="None">
<Run Text="10" FontSize="20" FontWeight="Bold"/>
</Hyperlink>
<Run Text="Text l" FontSize="20"/>
</Paragraph>
</RichTextBlock>
<Button x:Name="btnHighlight" Click="btnHighlight_Click" Content="Highlight" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"/>
<Button x:Name="btnRemoveHighlight" Click="btnRemoveHighlight_Click" Content="Remove" HorizontalAlignment="Left" Margin="110,10,0,0" VerticalAlignment="Top"/>
</Grid>
MainPage.xaml.cs:
private void btnHighlight_Click(object sender, RoutedEventArgs e)
{
int selectionStart = Rtb.SelectionStart.Offset;
int selectionEnd = Rtb.SelectionEnd.Offset;
int lenght = selectionEnd - selectionStart;
TextRange textRange = new TextRange() { StartIndex = selectionStart, Length = lenght };
TextHighlighter highlighter = new TextHighlighter();
highlighter.Background = new SolidColorBrush(Colors.Yellow);
highlighter.Ranges.Add(textRange);
Rtb.TextHighlighters.Add(highlighter);
}
private void btnRemoveHighlight_Click(object sender, RoutedEventArgs e)
{
Rtb.TextHighlighters.Clear();
}
提前致谢..!