Das WPF FlowDocument ist eine einfache Möglichkeit, um Fließtext in WPF darzustellen. Hier zeige ich Methoden, um Textdateien in ein FlowDocument einzulesen.
XAML:
<FlowDocumentScrollViewer x:Name="documentViewer" />
Loading of a text file:
string fileName = @"Lizenz.txt"; if (File.Exists(fileName)) { var run = new Run(File.ReadAllText(fileName)); var p = new Paragraph(run); var flowDocument = new FlowDocument(p); documentViewer.Document = flowDocument; }
Loading of an external XAML file:
string fileName = @"Lizenz.xaml"; using (var fs = File.OpenRead(fileName)) { documentViewer.Document = (FlowDocument)XamlReader.Load(fs); }
Loading of an RTF file:
string fileName = @"Lizenz.rtf"; if (File.Exists(fileName)) { var flowDocument = new FlowDocument(); var textRange = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd); using (FileStream fileStream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { textRange.Load(fileStream, DataFormats.Rtf); } documentViewer.Document = flowDocument; }