How to get the selected paragraph of FlowDocument?

Emon Haque 3,176 Reputation points
2021-09-21T13:20:19.07+00:00

In the MainWindow.xaml, I've these:

<FlowDocumentScrollViewer x:Name="scroll" PreviewMouseDoubleClick="onSelectionChanged">
    <FlowDocument x:Name="doc" FontSize="20"/>
</FlowDocumentScrollViewer>

and in MainWindow.cs these:

public partial class MainWindow : Window
{
    public MainWindow() {
        InitializeComponent();
        for (int i = 1; i < 51; i++) {
            doc.Blocks.Add(new Paragraph() {
                Tag = i,
                Inlines = { new Run(i +") " + "Para No. " + i) }
            });
        }
    }

    void onSelectionChanged(object sender, MouseButtonEventArgs e) {
        //Here I want to access the Paragraph in which Selection's made
        //var start = scroll.Selection.Start;
        //var end = scroll.Selection.End;
        //var range = new TextRange(start, end);
        //Debug.WriteLine(range.Text);
    }
}

I want to access the paragraph, where a word is selected by double clicking, to get the Tag no and the selected word's position (by splitting the text with the space).

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,854 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.2K Reputation points
    2021-09-21T16:01:00.757+00:00

    To get the paragraph and its tag:

    var p = scroll.Selection.Start.Paragraph;
    var tag = p.Tag;
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.