Creating a FlowDocument from Code-behind

So far, we've been creating our FlowDocument's directly in XAML. Representing a document in XAML makes sense, because XAML is so much like HTML, which is used all over the Internet to create pages of information. However, this obviously doesn't mean that you can't create FlowDocument's from Code-behind - you absolutely can, since every element is represented by a class that you can instantiate and add with good, old C# code.

As a bare minimum example, here's our "Hello, world!" example from one of the first articles, created from Code-behind instead of XAML:

<Window x:Class="WpfTutorialSamples.Rich_text_controls.CodeBehindFlowDocumentSample"
        Title="CodeBehindFlowDocumentSample" Height="200" Width="300">
        <FlowDocumentScrollViewer Name="fdViewer" />
using System;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;

namespace WpfTutorialSamples.Rich_text_controls
	public partial class CodeBehindFlowDocumentSample : Window
		public CodeBehindFlowDocumentSample()

			FlowDocument doc = new FlowDocument();

			Paragraph p = new Paragraph(new Run("Hello, world!"));
			p.FontSize = 36;

			p = new Paragraph(new Run("The ultimate programming greeting!"));
			p.FontSize = 14;
			p.FontStyle = FontStyles.Italic;
			p.TextAlignment = TextAlignment.Left;
			p.Foreground = Brushes.Gray;

			fdViewer.Document = doc;

A FlowDocument created from Code-behind and displayed in a FlowDocumentScrollViewer

When compared to the small amount of XAML required to achieve the exact same thing, this is hardly impressive:

    <Paragraph FontSize="36">Hello, world!</Paragraph>
    <Paragraph FontStyle="Italic" TextAlignment="Left" FontSize="14" Foreground="Gray">The ultimate programming greeting!</Paragraph>

That's beside the point here though - sometimes it just makes more sense to handle stuff from Code-behind, and as you can see, it's definitely possible.

^ Back to Top