TOC

This article is currently in the process of being translated into French (~49% done).

Contrôles RichText:

Creating a FlowDocument from Code-behind

Jusqu'à présent, nous avons créé notre FlowDocument directement en XAML. Représenter un document en XAML est logique puisque XAML est très similaire à HTML et que ce dernier est utilisé partout sur Internet pour créer des pages d'informations. Par contre, ça ne veut pas que vous ne pouvez pas créer de FlowDocument à partir du Code-behind. C'est tout à fait possible puisque chaque élément est représenté par une classe que vous pouvez instancier et ajouter avec du bon, vieux code C#.

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;
		}
	}
}

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.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!