TOC

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

Kontrolki Rich Text:

Creating a FlowDocument from Code-behind

Do tej pory tworzyliśmy dokumenty FlowDocument bezpośrednio w XAML. To podejście ma sens, bo XAML jest bardzo podobny do języka HTML, który jest używany do tworzenia stron internetowych na całym świecie. Nie znaczy to jednak, że FlowDocument nie da się stworzyć z Code-behind. Ponieważ wszystkie jego elementy są klasami, możemy je zainicjować, a potem dodać ze starym dobrym C#.

Aby ten przykład był prosty, odtworzymy teraz za pomocą kodu dokument z jednego z pierwszych artykułów o FlowDocument:

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

Nie jest to zbytnio imponujące, jeśli porównamy ilość kodu XAML i C# do stworzenia tego samego dokumentu:

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

Takie porównanie nie ma jednak sensu - czasami po prostu logiczniejsze jest stworzenie czegoś w Code-behind niż w XAML. Ten artykuł pokazuje Ci, że jest to jak najbardziej możliwe.


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!