what is the most simple and elegant way how convert flowdocument to simple text?
Wpf – Convert FlowDocument to simple text
flowdocumentwpf
Related Solutions
You should not persist the FlowDocument directly as it should be considered the runtime representation of the document, not the actual document content. Instead, use the TextRange class to Save and Load to various formats including Rtf.
A quick sample on how to create a selection and save to a stream:
var content = new TextRange(doc.ContentStart, doc.ContentEnd);
if (content.CanSave(DataFormats.Rtf))
{
using (var stream = new MemoryStream())
{
content.Save(stream, DataFormats.Rtf);
}
}
To load content into a selection would be similar:
var content = new TextRange(doc.ContentStart, doc.ContentEnd);
if (content.CanLoad(DataFormats.Rtf))
{
content.Load(stream, DataFormats.Rtf);
}
I had the same problem and managed to get something like the following to work:
public class MyRichTextBox : RichTextBox
{
public MyRichTextBox()
: base()
{
CommandManager.RegisterClassCommandBinding(typeof(MyRichTextBox),
new CommandBinding(ApplicationCommands.Copy, OnCopy, OnCanExecuteCopy));
}
private static void OnCanExecuteCopy(object target, CanExecuteRoutedEventArgs args)
{
MyRichTextBox myRichTextBox = (MyRichTextBox)target;
args.CanExecute = myRichTextBox.IsEnabled && !myRichTextBox.Selection.IsEmpty;
}
private static void OnCopy(object sender, ExecutedRoutedEventArgs e)
{
MyRichTextBox myRichTextBox = (MyRichTextBox)sender;
Clipboard.SetText(GetInlineText(myRichTextBox));
e.Handled = true;
}
private static string GetInlineText(RichTextBox myRichTextBox)
{
StringBuilder sb = new StringBuilder();
foreach (Block b in myRichTextBox.Document.Blocks)
{
if (b is Paragraph)
{
foreach (Inline inline in ((Paragraph)b).Inlines)
{
if (inline is InlineUIContainer)
{
InlineUIContainer uiContainer = (InlineUIContainer)inline;
if (uiContainer.Child is Button)
sb.Append(((Button)uiContainer.Child).Content);
}
else if (inline is Run)
{
Run run = (Run)inline;
sb.Append(run.Text);
}
}
}
}
return sb.ToString();
}
}
Of course this is very simplistic - you would probably create a subclass of Button and define an interface-function like "GetCopyToClipboardText" instead of having the "how to get text from a button"-code inside the richtextbox.
The example copies all text inside the richtextbox - it would be more usefull if only the selected part of the textbox was copied to the clipboard. This post gives an example of how to achive that.
Best Answer
How about this?