The community is working on translating this tutorial into Bulgarian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".
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"
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.