Search code examples
c#wpfreturncpu-wordbold

How can I return only the bold words in the body of a RichTextBox in WPF?


private void SubmitButton_Click(object sender, RoutedEventArgs e)
        {
           
            myWeb.Source = new Uri ("https://www.google.com/search?tbm=isch&q=" + titleWord.Text + " " + boldWord.Text);

        }

I got a button that searches google images. There is a textbox input for a Title (named titleWord) and a RichTextBox input (with the Run named boldWord). I only want the bold words in the RichTextBox to be searched, not the whole text.

<RichTextBox Grid.ColumnSpan="2" Grid.Column="1" HorizontalAlignment="Left" Height="150" Margin="10,4,0,0" Grid.Row="2" VerticalAlignment="Top" Width="220">
            <FlowDocument>
                <Paragraph>
                    <Run Name="boldWord" />
                </Paragraph>
            </FlowDocument>
        </RichTextBox>

Solution

  • Your answer here is Find Bold Text And I put another method. You should scroll through a set of InlineCollection inside the paragraphs and find texts that have the features you want.

    xaml code for test

    <RichTextBox x:Name="rchTextbox" Grid.ColumnSpan="2" Grid.Column="1" HorizontalAlignment="Left" Height="150" Margin="10,4,0,0" Grid.Row="2" VerticalAlignment="Top" Width="220">
       <FlowDocument>
           <Paragraph>
               <Run Text="Normal Text 1" />
               <Run Text="Bold Test 1" FontWeight="Bold"></Run>
               <Run Text=" Normal Text 2" FontWeight="Normal"></Run>
               <Run Text="Bold Text 2" FontWeight="Bold"></Run>
            </Paragraph>
       </FlowDocument>
    </RichTextBox>
    

    and .cs code

    List<string> boldTexts = new List<string>();
    foreach (Paragraph p in rchTextbox.Document.Blocks)
    {
        foreach (var inline in p.Inlines)
        {
           if (inline.FontWeight == FontWeights.Bold)
           {
               var textRange = new TextRange(inline.ContentStart, inline.ContentEnd);
               boldTexts.Add(textRange.Text);
               MessageBox.Show(textRange.Text);
           }
        }
    }