Visual Basic 2010 : Manipulating Documents and Media - Manipulating Documents
Illustrating how you can create flow documents
Illustrating how you can add and format text within flow documents
Implementing features for adding annotations to documents and saving them to disk
Add a new Window to the current one, setting it as the startup page. When ready, write the XAML code shown in Listing 1 that implements the UI side of the application. The code is explained at the end of the listing.
Listing 1. Implementing Flow Documents
Let’s begin by illustrating the FlowDocumentReader control. It basically provides a container for flow documents and automatically implements buttons for browsing multiple page documents and controlling documents’ layout, as you see later in Figure 1. The FlowDocument object instead contains the document and exposes some interesting properties. The previous code uses the most important ones. TextAlignment enables specifying how the text must be aligned within the document and can have one of the following values: Center, Right, Left, or Justify. IsOptimalParagraph set as True enables paragraph layout optimization. IsHyphenationEnable set as True enables word hyphenation in the document. IsColumnWidthFlexible set as True means that the value of the ColumnWidth property is not fixed. This last property takes place when you enable the document view by columns. The ColumnGap property indicates the spacing between columns. A complete list of properties is available in the MSDN Library: http://msdn.microsoft.com/en-us/library/system.windows.documents.flowdocument_members(VS.100).aspx. For the document content, notice the following techniques:
You divide the content into multiple Paragraph objects to provide different paragraph formatting.
You can add inline formatting. For example, the following line contains bold formatting within a paragraph:
<Bold>PresentationFramework</Bold> exposes namespaces and classes
You can also add fully functional hyperlinks as in the following sample line:
<Hyperlink
NavigateUri="http://msdn.microsoft.com/en-
us/library/ms750441(VS.100).aspx#System_Threading_DispatcherObject">
System.Threading.DispatcherObject</Hyperlink>
Figure 1. Viewing and annotating a flow document.
The sample document also shows how to implement bulleted lists via a List object that contains ListItem elements. It is interesting how flow documents also support figures insertion via a Figure element that contains a BlockUIContainer object nesting an Image control storing the figure and a TextBlock control describing the figure. Notice how each paragraph and subparagraph can be customized by setting font properties different from other paragraphs. Switching the discussion to buttons implementation, instead of handling Click events the code makes use of a technique known as commanding that takes advantage of built-in commands associated to specific actions; basically each button is associated to one of the built-in actions for the annotation service via the Command property and points to the flow document as the target of the action (CommandTarget). At this point there is the need of writing code that enables the annotation service at the application startup so that the user can annotate or highlight text and then save annotations to disk for later reuse. The annotation service relies on the System.Windows.Annotations namespace that provides an AnnotationService class whose instance allows editing the document. Next, the System.Windows.Annotations.Storage namespace provides objects for storing annotations to Xml files for later reuse. Code in Listing 2 shows how to implement the annotation service with Visual Basic. The code must be written to the code-behind file for the current window and contains comments for better reading.
Listing 2. Implementing the Annotation Service
Notice how the annotation service startup is placed inside the Window.Initialized event handler, whereas the annotation service shutdown is placed inside the Windows.Closed event handler. Now run the demo application by pressing F5. As you can see on the screen, if you resize the window, the flow document content is automatically and dynamically adapted to the window’s layout. Moreover you can decide, using the appropriate controls on the FlowDocumentReader, how the document has to be viewed (for example if one or two pages appear on the window or with zoom enabled). The best way for getting a feeling about how this works is to resize the window. Figure 1 shows how the application looks, showing also an example of annotation.
You can also add ink annotations to your documents. Figure 2 shows how ink annotations look and how text is exposed with fonts different than the standard one. Also notice how the hyperlink is correctly highlighted and functional so that if you click it you will be redirected to the related web page associated via the NavigateUri property in the XAML code.
Figure 2. Adding ink notes and viewing formatted text.
Annotations are automatically stored into an Xml file, as implemented in code. Remember to resize the window to understand the flexibility of flow documents and of the FlowDocumentReader control.
Understanding the RichTextBox Control
WPF offers a RichTextBox control that works as you would expect for some aspects, thus allowing advance formatting and image support, but it differs from other technologies in that such control stores its content as a flow document. In XAML code the control definition looks like this:
<RichTextBox Name="RichTextBox1">
<!— add your flow document here —>
</RichTextBox>
You could nest within the control the flow document shown in the previous section to get a fully editable document or simply write your text into the control, where such text takes standard formatting settings. You can also load an existing file into the RichTextBox, which requires some lines of code. The following method shows how to load a document as text:
Private Sub LoadDocument(ByVal fileName As String)
Dim range As TextRange
If File.Exists(fileName) Then
range = New TextRange(RichTextBox1.Document.ContentStart,
RichTextBox1.Document.ContentEnd)
Using documentStream As New FileStream(fileName,
FileMode.
OpenOrCreate)
range.Load(documentStream,
System.Windows.DataFormats.Text)
End Using
End If
End Sub
The TextRange class basically represents the text area, and the code takes the entire area from start to end. Then the code invokes the TextRange.Load method to open the specified stream and converts the file content into a System.Windows.DataFormats.Text format that is acceptable for the RichTextBox. Notice that the previous example loads a text document that is then converted into XAML by the runtime. You can also load contents from XAML files using the DataFormats.Xaml option. To save the document content you need to invoke the TextRange.Save method. The following method shows an example:
Private Sub SaveDocument(ByVal fileName As String)
Dim range As New TextRange(Me.RichTextBox1.Document.ContentStart,
Me.RichTextBox1.Document.ContentEnd)
Using documentStream As New FileStream(fileName,
FileMode.Create)
range.Save(documentStream, DataFormats.Xaml)
End Using
End Sub
In this case the document content is saved under the form of XAML content but you can still use the Text option to save such content as text, although this can cause a loss of formatting settings due to the restrictive conversion.
Implementing Spell Check
The RichTextBox control provides built-in spell check support. This can be enabled by setting the SpellCheck.IsEnabled property as follows:
<RichTextBox Name="RichTextBox1" SpellCheck.IsEnabled="True">
When enabled, when the user types unrecognized words in the English grammar the words are highlighted in red, and by right-clicking the highlighted word a list of valid alternatives is suggested, similar to what happens in applications such as Microsoft Word. Figure 3 shows how the spell check feature can help users to fix typos in their documents.