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

Controles de texto enriquecido:

Creating a FlowDocument from Code-behind

Hasta ahora, hemos estado creando nuestros FlowDocument directamente en XAML. Representar un documento en XAML tiene sentido, porque XAML es muy parecido a HTML, el cual es utilizado en Internet para crear páginas WEB. Sin embargo, esto no significa que no se pueda crear FlowDocument desde Code-behind. Es absolutamente posible, ya que cada elemento está representado por una clase que puede ser instanciada y añadida con un buen código en 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"
        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;

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.

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!