【发布时间】:2018-07-05 18:31:48
【问题描述】:
我想在保持相同格式的同时突出显示文本:粗体、下划线、斜体……但我只是通过丢失格式来突出显示文本。得到我想要的内容是否正确,或者是否有另一种方法可以突出显示文本而不必“拆分”它然后重新组合?
xaml:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Width="300">
<RichTextBlock x:Name="RichTextBlockText">
<Paragraph x:Name="Testo">
<Run Foreground="Gray" FontFamily="Segoe UI Light" FontSize="24">
This is a
</Run>
<Run Foreground="Teal" FontFamily="Georgia" FontSize="18" FontStyle="Italic">
different text
</Run>
<Run Foreground="Black" FontFamily="Arial" FontSize="14" FontWeight="Bold">
format
</Run>
</Paragraph>
</RichTextBlock>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Center" Margin="0,25,0,0">
<TextBox x:Name="txbToFind" Height="32" VerticalAlignment="Bottom" Width="200" HorizontalAlignment="Left"/>
<Button x:Name="btnFind" Content="Find" Click="btnFind_Click" HorizontalAlignment="Right" VerticalAlignment="Center"/>
</Grid>
</StackPanel>
</Grid>
xaml.cs:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void btnFind_Click(object sender, RoutedEventArgs e)
{
string text = string.Empty;
TextBlock NewText = new TextBlock();
string toFind = txbToFind.Text;
for (int a = 0; a <= Testo.Inlines.Count - 1; a++)
{
Run runCorrente = Testo.Inlines[a] as Run;
string currentText;
currentText = runCorrente.Text;
text += currentText;
}
if (text.IndexOf(toFind) >= 0)
{
string[] partOfText = text.Split(new String[] { toFind }, StringSplitOptions.None);
Paragraph paragraph = new Paragraph();
for (int a = 0; a <= partOfText.Length - 1; a++)
{
var piece = partOfText[a];
Run run = new Run();
run.Text = piece;
paragraph.Inlines.Add(run);
if (a < partOfText.Length - 1)
{
MakeHighlightedParagraph(paragraph, toFind, RichTextBlockText);
}
}
RichTextBlockText.Blocks.Clear();
RichTextBlockText.Blocks.Add(paragraph);
}
}
private void MakeHighlightedParagraph(Paragraph paragraph, string textToHighlight, RichTextBlock textBlock)
{
InlineUIContainer cont = new InlineUIContainer();
var border = new Border();
border.MinWidth = textBlock.FontSize / 3.5;
border.Background = new SolidColorBrush(Colors.Yellow);
var text = new TextBlock();
text.Text = textToHighlight;
var margin = textBlock.FontSize * (3.0 / 14.0) + 1.0;
text.Margin = new Thickness(0.0, 0.0, 0.0, -margin);
border.Child = text;
cont.Child = border;
paragraph.Inlines.Add(cont);
}
}
提前谢谢...!
我找到了一些可能的解决方案,但我无法使用它们:
TextRange - 选择文本的一部分; TextHighlighter - 突出显示一个或多个文本范围。
但是它们是如何使用的呢?请帮帮我..!
【问题讨论】: