TOC

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

Các điều khiển Rich Text:

Creating a FlowDocument from Code-behind

Đến đây, chúng ta đã tạo được FlowDocument trực tiếp bằng XAML. Việc trình bày một document với XAML thì dễ hiểu, vì XAML rất giống HTML được dùng trên internet để tạo các trang web. Tuy nhiên, điều đó không có nghĩa là bạn không thể tạo FlowDocument bằng code - chắc chắn bạn có thể, vì mỗi phần tử được mô tả bằng một class mà bạn có thể khởi tạo và thêm vào bằng code C#.

Dưới đây là một ví dụ đơn giản "Hello, world!" tạo bằng code thay vì 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;
		}
	}
}

Code-behind thật khó mà tạo được ấn tượng tốt, khi so với XAML chỉ cần chút mã để làm được cũng một điều đó:

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

Tuy nhiên, như bạn biết, chắc chắn là có những lúc phải dùng đến code để giải quyết vấn đề.


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!