This article has been localized into Chinese by the community.
Rich Text控件:
从后台代码创建FlowDocument
到目前为止,我们一直在XAML中创建FlowDocument。 在XAML中表示文档是情理之中的,因为XAML非常像HTML,它在整个Internet上用于创建信息页面。 但是,这并不意味着您无法从后台代码创建FlowDocument - 您完全可以,因为每个元素都是一个类,您可以使用C#代码进行实例化和添加。
作为一个最基本的例子,这是我们的“Hello,world!” 从后台代码而不是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;
}
}
}
实现完全相同的东西对比XAML的简洁,这真是难以置信:
<FlowDocument>
<Paragraph FontSize="36">Hello, world!</Paragraph>
<Paragraph FontStyle="Italic" TextAlignment="Left" FontSize="14" Foreground="Gray">The ultimate programming greeting!</Paragraph>
</FlowDocument>
这不是重点 - 有时候适合用后台代码处理,如您所见,它也能实现。
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!