Wpf – How to get the selected text of a WPF FlowDocument

copyflowdocumentwpf

I'm using .NET 3.5

I have a FlowDocument inside a FlowDocumentScrollViewer. I am not using RichTextBox. The FlowDocument comes with a number of "freebies", including text selection and a context menu for copy/paste.

How can I find out what text is currently selected in the FlowDocument? I imagine that I could use ApplicationCommands.Copy to get the text into the clipboard and then read it from there, but I don't want to change the contents of the clipboard if I don't have to.

There must be something I'm missing…

Best Answer

What version of .net framework are you using? Since version 3.5 there is Selection property introduced for FlowDocumentScrollViewer control. You can use it to work with selected text, smth like this:

TextPointer potStart = flowDocumentScrollViewer.Selection.Start;
TextPointer potEnd = flowDocumentScrollViewer.Selection.End;
TextRange range = new TextRange(potStart,potEnd);
Console.WriteLine(range.Text);

hope this helps, regards

Related Topic