WPF FlowDocumentReader Loading Text File In VB.NET
In this article, I demonstrate how to load a text file in a FlowDocumentReader available in WPF using VB.NET.
The attached project is a WPF application written in C# and XAML. It uses OpenFileDialog to browse text files and once text file is selected, it is loaded in a FlowDocumentReader that allows you to view, paging, and find options.
First, let's create a UI with a TextBox, a Button, and a FlowDocumentViewer control.
The UI looks like Figure 1.
Figure 1
The XAML code for the UI looks like this.
<Window x:Class="LoadTextFileInFlowDocumentViewerSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="290" Width="600">
<Canvas>
<TextBox Height="32" HorizontalAlignment="Left" Margin="6,10,0,0" Name="FileNameTextBox"
VerticalAlignment="Top" Width="393" />
<Button Content="Browse" Height="32" HorizontalAlignment="Left" Margin="405,10,0,0"
Name="button1" VerticalAlignment="Top" Width="88" Click="button1_Click" />
<FlowDocumentReader Name="FlowDocReader" Background="LightBlue"
Canvas.Top="50" Canvas.Left="5" Width="560"
Height="210">
</FlowDocumentReader>
</Canvas>
</Window>
On Button control, we will browse a text file and set TextBox.Text property to the selected file. As you can see from code below, we create a Paragraph and add the selected text file using Paragraph.Inlines.Add method. After that, we create a FlowDocument by passing this Paragraph and in the end; we set FlowDocumentReader.Document property to the FlowDocument.
Code sample in VB.NET
Private Sub button1_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
' Create OpenFileDialog
Dim dlg As New Microsoft.Win32.OpenFileDialog()
' Set filter for file extension and default file extension
dlg.DefaultExt = ".txt"
dlg.Filter = "Text documents (.txt)|*.txt"
' Display OpenFileDialog by calling ShowDialog method
Dim result As Nullable(Of Boolean) = dlg.ShowDialog()
' Get the selected file name and display in a TextBox
If result = True Then
' Open document
Dim filename As String = dlg.FileName
FileNameTextBox.Text = filename
Dim paragraph As New Paragraph()
paragraph.Inlines.Add(System.IO.File.ReadAllText(filename))
Dim document As New FlowDocument(paragraph)
FlowDocReader.Document = document
End If
End Sub
Now if you run the application and browse a text file, the output looks like Figure 2.
Figure 2