fastread homefastrread library fastread menu

WPF : Creating a FlowDocument from Code-behind

Tutorial by:Manisha Dubey      Date: 2016-07-11 23:23:02

❰ Previous Next ❱

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"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="CodeBehindFlowDocumentSample" Height="200" Width="300">
    <Grid>
        <FlowDocumentScrollViewer Name="fdViewer" />
    </Grid>
</Window>
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()
		{
			InitializeComponent();

			FlowDocument doc = new FlowDocument();

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

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

			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:

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

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.

❰ Previous Next ❱


WPF

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website