Опубликован: 05.08.2010 | Уровень: специалист | Доступ: платный
Самостоятельная работа 10:

Текст WPF

Использование контейнера FlowDocumentPageViewer

Использование контейнера FlowDocumentPageViewer для FlowDocument позволяет представлять документ как одну страницу без средства поиска текста и разбивки его на страницы и колонки, но оставляет панель изменения масштаба и навигации. Однако в самом FlowDocument есть свойства, позволяющие настраивать обычный и многоколоночный текст. Вот некоторые из них

  • TextAlignment="Justify" - выравнивание текста по обеим границам колонок (включен по умолчанию)
  • IsHyphenationEnabled="True" - включение расстановки переносов (при наличии словарей)
  • IsOptimalParagraphEnabled="True" - включение оптимального абзаца, выравнивающего пробелы между словами за счет разрежения символов в самих словах при режиме TextAlignment="Justify"
  • ColumnGap="25" - ширина между колонками в логических пикселах
  • ColumnWidth="150" - предпочтительная (минимальная) ширина колонки
  • IsColumnWidthFlexible="False" - это значение флага явно запрещает дозаполнять окно просмотра и устанавливает жесткую ширину колонки
  • ColumnRuleWidth="5" - ширина вертикальных линеек, разделяющих колонки текста
  • ColumnRuleBrush="Red" - цвет линеек
  • В контейнер <TabControl> добавьте вкладку <TabItem Header="Text4"> и заполните ее следующим кодом
<TabItem Header="Text4">
            <FlowDocumentPageViewer>
                <FlowDocument 
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    Background="White"
                    ColumnWidth="150"
                    ColumnRuleWidth="2"
                    ColumnRuleBrush="Red"
                    ColumnGap="30"
                    IsHyphenationEnabled="True"
                    IsOptimalParagraphEnabled="True"
                    >
                    <Paragraph FontSize="18" FontWeight="Bold" TextAlignment="Center">
                        Примеры форматирования FlowDocument &amp; FlowDocumentPageViewer
                    </Paragraph>
                    <Paragraph>
                          Это абзац с атрибутами по умолчанию.
                    </Paragraph>
                    <Paragraph>
                          Это еще один абзац с атрибутами по умолчанию.
                    </Paragraph>
                    <Paragraph FontSize="18">Абзац с FontSize="18"</Paragraph>
                    <Paragraph FontSize="15">Абзац с FontSize="15"</Paragraph>
                    <Paragraph FontSize="15">Список &lt;List FontFamily="Arial"&gt;</Paragraph>
                    <List FontFamily="Arial">
                        <ListItem>
                            <Paragraph>ListItem 1</Paragraph>
                        </ListItem>
                        <ListItem>
                            <Paragraph>ListItem 2</Paragraph>
                        </ListItem>
                        <ListItem>
                            <Paragraph>ListItem 3</Paragraph>
                        </ListItem>
                        <ListItem>
                            <Paragraph>ListItem 4</Paragraph>
                        </ListItem>
                        <ListItem>
                            <Paragraph>ListItem 5</Paragraph>
                        </ListItem>
                    </List>
                    <Paragraph>
                        <Bold>Это элемент &lt;Bold&gt; внутри абзаца &lt;Paragraph&gt;</Bold>
                    </Paragraph>
                    <Paragraph>
                        <Underline>Это элемент Underline внутри абзаца</Underline>
                    </Paragraph>
                    <Paragraph>
                        <Bold>
                            <Underline>Подчеркнутый внутри полужирного</Underline>
                        </Bold>
                    </Paragraph>
                    <Paragraph>
                        <Italic>Это элемент &lt;Italic&gt;</Italic>
                    </Paragraph>
                    <Paragraph>
                        <Span>Элемент Span с настройками по умолчанию</Span>
                    </Paragraph>
                    <Paragraph>
                        <Run>Элемент Run с настройками по умолчанию</Run>
                    </Paragraph>
                    <Paragraph FontSize="15">Subscript, Superscript</Paragraph>
                    <Paragraph>
                        <Run Typography.Variants="Superscript">This text is Superscripted.</Run> 
                        This text isn't.
                    </Paragraph>
                    <Paragraph>
                        <Run Typography.Variants="Subscript">This text is Subscripted.</Run> 
                        This text isn't.
                    </Paragraph>
                    <Paragraph TextIndent="-25" Margin="25,0">
                        If a font does not support a particular form (such as Superscript) 
                        a default font form will be displayed.
                    </Paragraph>
                    <Paragraph FontSize="15">Blocks, breaks, paragraph</Paragraph>
                    <Section>
                        <Paragraph>A block section of text</Paragraph>
                    </Section>
                    <Section>
                        <Paragraph>Another block section of text</Paragraph>
                    </Section>
                    <Paragraph>
                        <LineBreak/>
                    </Paragraph>
                    <Section>
                        <Paragraph>... and another section, preceded by a LineBreak</Paragraph>
                    </Section>
                    <Section BreakPageBefore="True"/>
                    <Section>
                        <Paragraph>... and another section, preceded by a PageBreak</Paragraph>
                    </Section>
                    <Paragraph>Finally, a paragraph. Note the break between this paragraph ...</Paragraph>
                    <Paragraph TextIndent="25">... and this paragraph, and also the left indention.</Paragraph>
                </FlowDocument>
            </FlowDocumentPageViewer>
        </TabItem>

Здесь мы применили основной набор элементов форматирования текста 'на лету'. Обратите внимание, что в разметке угловые скобки кодируются как в HTML. Другие управляющие символы разметки кодируются аналогично, например, ' & ' кодируется как ' &amp; '. Знак подчеркивания ' _ ' считается служебным для выделения горячих клавиш в меню, поэтому в ином употреблении должен экранироваться таким же знаком подчеркивания.

Параметры настройки FlowDocument разбивают текст на колонки, задают ширину колонок, расстояние между ними и вертикальные линейки. Определение пространств имен в дескрипторе FlowDocument здесь роли не играет, но должно обязательно присутствовать для успокоения редактора, если контейнер FlowDocument редактируется оболочкой автономно как внешний файл документа.

  • Запустите приложение, поизменяйте размер окна и разберитесь с кодом

Результат будет таким

Обратите внимание, что в длинных словах кириллический текст объект FlowDocument не переносит, а латиницу - переносит.

  • Проверьте действие атрибута IsOptimalParagraphEnabled="True", включающего оптимальный параграф

Пример из MSDN

Следующий пример взят из MSDN (http://msdn.microsoft.com/ru-ru/library/system.windows.controls.flowdocumentscrollviewer.aspx) и иллюстрирует дополнительные возможности разметки неформатированного текста в FlowDocument. Он не содержит кириллицы, поэтому дальше нам пригодится при решении проблем кодировки.

  • Добавьте новую вкладку с приведенным кодом
<TabItem Header="Text5" Selector.IsSelected="True">
            <FlowDocumentScrollViewer Margin="10" BorderBrush="Black" BorderThickness="1">
                <FlowDocument 
                    ColumnWidth="400" 
                    IsOptimalParagraphEnabled="True" 
                    IsHyphenationEnabled="True"
                    >
                    <Section FontSize="12">
                        <Paragraph>
                            <Bold>Neptune</Bold> (planet), major planet in the solar system, eighth planet
                            from the Sun and fourth largest in diameter.  Neptune maintains an almost constant
                            distance, about 4,490 million km (about 2,790 million mi), from the Sun.  Neptune
                            revolves outside the orbit of Uranus and for most of its orbit moves inside the
                            elliptical path of the outermost planet Pluto (see Solar System). Every 248 years,
                            Pluto’s elliptical orbit brings the planet inside Neptune’s nearly circular orbit
                            for about 20 years, temporarily making Neptune the farthest planet from the Sun.
                            The last time Pluto’s orbit brought it inside Neptune’s orbit was in 1979. In
                            1999 Pluto’s orbit carried it back outside Neptune’s orbit.
                            <Figure 
                                  Width="140" Height="50" Background="GhostWhite" 
                                  HorizontalAnchor="PageLeft" 
                                  HorizontalOffset="100" VerticalOffset="20"
                                  >
                                <Paragraph 
                                    FontStyle="Italic" TextAlignment="Left"
                                    Background="Beige" Foreground="DarkGreen"
                                    >
                                    Neptune has 72 times Earth's volume...
                                </Paragraph>
                            </Figure>
                            
                            <Floater 
                                Background="GhostWhite" 
                                Width="285" HorizontalAlignment="Left"
                                >
                                <Table CellSpacing="5">
                                    <Table.Columns>
                                        <TableColumn Width="155"/>
                                        <TableColumn Width="130"/>
                                    </Table.Columns>
                                    
                                    <TableRowGroup>
                                        <TableRow>
                                            <TableCell ColumnSpan="3">
                                                <Paragraph>Neptune Stats</Paragraph>
                                            </TableCell>
                                        </TableRow>
                                        
                                        <TableRow Background="LightGoldenrodYellow" FontSize="12">
                                            <TableCell>
                                                <Paragraph FontWeight="Bold">Mean Distance from Sun</Paragraph>
                                            </TableCell>
                                            <TableCell>
                                                <Paragraph>4,504,000,000 km</Paragraph>
                                            </TableCell>
                                        </TableRow>
                                        
                                        <TableRow FontSize="12" Background="LightGray">
                                            <TableCell>
                                                <Paragraph FontWeight="Bold">Mean Diameter</Paragraph>
                                            </TableCell>
                                            <TableCell>
                                                <Paragraph>49,532 km</Paragraph>
                                            </TableCell>
                                        </TableRow>
                                        
                                        <TableRow Background="LightGoldenrodYellow" FontSize="12">
                                            <TableCell>
                                                <Paragraph FontWeight="Bold">Approximate Mass</Paragraph>
                                            </TableCell>
                                            <TableCell>
                                                <Paragraph>1.0247e26 kg</Paragraph>
                                            </TableCell>
                                        </TableRow>
                                        <TableRow>
                                            <TableCell ColumnSpan="4">
                                                <Paragraph FontSize="10" FontStyle="Italic">
                                                    Information from the
                                                    <Hyperlink 
                                                        NavigateUri="http://encarta.msn.com/encnet/refpages/artcenter.aspx"
                                                        >
                                                        Encarta
                                                    </Hyperlink>
                                                    web site.
                                                </Paragraph>
                                            </TableCell>
                                        </TableRow>
                                    </TableRowGroup>
                                </Table>
                            </Floater>
                        </Paragraph>
                        <Paragraph>
                            Astronomers believe Neptune has an inner rocky core that is surrounded by a vast
                            ocean of water mixed with rocky material. From the inner core, this ocean extends
                            upward until it meets a gaseous atmosphere of hydrogen, helium, and trace amounts
                            of methane. Neptune has four rings and 11 known moons. Even though Neptune's volume
                            is 72 times Earth’s volume, its mass is only 17.15 times Earth’s mass. Because of
                            its size, scientists classify Neptune—along with Jupiter, Saturn, and Uranus—as
                            one of the giant or Jovian planets (so-called because they resemble Jupiter).
                        </Paragraph>
                        <Paragraph>
                            <Figure 
                                Width="140" Height="50" 
                                Background="GhostWhite" TextAlignment="Left" 
                                HorizontalAnchor="PageCenter" WrapDirection="Both"
                                >
                                <Paragraph FontStyle="Italic" Background="Beige" Foreground="DarkGreen" >
                                    Neptune has an orbital period of ~20 years...
                                </Paragraph>
                            </Figure>
                            Mathematical theories of astronomy led to the discovery of Neptune. To account for
                            wobbles in the orbit of the planet Uranus, British astronomer John Couch Adams and
                            French astronomer Urbain Jean Joseph Leverrier independently calculated the existence
                            and position of a new planet in 1845 and 1846, respectively. They theorized that the
                            gravitational attraction of this planet for Uranus was causing the wobbles in Uranus’s
                            orbit. Using information from Leverrier, German astronomer Johann Gottfried Galle first
                            observed the planet in 1846.
                        </Paragraph>
                    </Section>
                </FlowDocument>
            </FlowDocumentScrollViewer>
        </TabItem>
  • Запустите приложение - результат будет таким

  • Поизменяйте размер окна и разберитесь с кодом

Описание использованных в примере элементов можно найти на http://msdn.microsoft.com/ru-ru/library/system.windows.documents.aspx

Алексей Бабушкин
Алексей Бабушкин

При выполнении в лабораторной работе упражнения №1 , а именно при выполнении нижеследующего кода:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using Microsoft.Xna.Framework.Graphics;

   

namespace Application1

{

    public partial class MainForm : Form

    {

        // Объявим поле графического устройства для видимости в методах

        GraphicsDevice device;

   

        public MainForm()

        {

            InitializeComponent();

   

            // Подпишемся на событие Load формы

            this.Load += new EventHandler(MainForm_Load);

   

            // Попишемся на событие FormClosed формы

            this.FormClosed += new FormClosedEventHandler(MainForm_FormClosed);

        }

   

        void MainForm_FormClosed(object sender, FormClosedEventArgs e)

        {

            //  Удаляем (освобождаем) устройство

            device.Dispose();

            // На всякий случай присваиваем ссылке на устройство значение null

            device = null;       

        }

   

        void MainForm_Load(object sender, EventArgs e)

        {

            // Создаем объект представления для настройки графического устройства

            PresentationParameters presentParams = new PresentationParameters();

            // Настраиваем объект представления через его свойства

            presentParams.IsFullScreen = false; // Включаем оконный режим

            presentParams.BackBufferCount = 1;  // Включаем задний буфер

                                                // для двойной буферизации

            // Переключение переднего и заднего буферов

            // должно осуществляться с максимальной эффективностью

            presentParams.SwapEffect = SwapEffect.Discard;

            // Устанавливаем размеры заднего буфера по клиентской области окна формы

            presentParams.BackBufferWidth = this.ClientSize.Width;

            presentParams.BackBufferHeight = this.ClientSize.Height;

   

            // Создадим графическое устройство с заданными настройками

            device = new GraphicsDevice(GraphicsAdapter.DefaultAdapter, DeviceType.Hardware,

                this.Handle, presentParams);

        }

   

        protected override void OnPaint(PaintEventArgs e)

        {

            device.Clear(Microsoft.Xna.Framework.Graphics.Color.CornflowerBlue);

   

            base.OnPaint(e);

        }

    }

}

Выбрасывается исключение:

Невозможно загрузить файл или сборку "Microsoft.Xna.Framework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=6d5c3888ef60e27d" или один из зависимых от них компонентов. Не удается найти указанный файл.

Делаю все пунктуально. В чем может быть проблема?

Иван Циферблат
Иван Циферблат
Россия, Таганрог, 36, 2000