question

EmonHaque-1485 avatar image
0 Votes"
EmonHaque-1485 asked Viorel-1 commented

How to get the selected paragraph of FlowDocument?

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-wpf
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Viorel-1 avatar image
1 Vote"
Viorel-1 answered Viorel-1 commented

To get the paragraph and its tag:

 var p = scroll.Selection.Start.Paragraph;
 var tag = p.Tag;

· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

still couldn't find the way to get the selected text and word position. Tried this:

 void onSelectionChanged(object sender, MouseButtonEventArgs e) {
     var start = scroll.Selection.Start;
     var end = scroll.Selection.End;
     var range = new TextRange(start, end);
     var para = start.Paragraph;
     Debug.WriteLine(para.Tag + " " + range.Text);
 }

but there's no output for range.Text;

EDIT


I get the selected text if I wrap the flow document in a RichTextBox instead of FlowDocumentScrollViewer.

0 Votes 0 ·
Viorel-1 avatar image Viorel-1 EmonHaque-1485 ·

In case of FlowDocumentScrollViewer, try handling MouseDoubleClick. But a read-only RichTextBox is probably more convenient.

1 Vote 1 ·