Загрузка FlowDocument из XAML-файла

Документ нефиксированного формата можно создать заранее в XAML -редакторе, сохранить его в файле и загружать во время выполнения в элемент управления просмотром. Продемонстрируем это на предыдущем примере.

  • Добавьте в разметку новую вкладку следующего содержания (атрибут подписки на событие Initialized введите вручную, чтобы правильно создать обработчик)
<TabItem Header="Text6" Selector.IsSelected="True"> <FlowDocumentScrollViewer Margin="10" BorderBrush="Black" BorderThickness="1" Initialized="FlowDocumentScrollViewer_Initialized" Name="documentReader" /> </TabItem>

Здесь мы декларативно определили и настроили пустой именованный контейнер просмотра документа, а сам документ с содержимым FlowDocument загрузим из файла программно и присоединим к свойству Document этого контейнера просмотра.

  • Уберите из предыдущей вкладки атрибут Selector.IsSelected="True", чтобы при запуске приложения сразу открывалась вкладка Text6
  • Добавьте к проекту WpfText2 новый XML -файл с именем XMLFile1.xml и измените его расширение c xml на xaml
  • Выделите новый файл и измените через панель Properties его свойства на
    • Build Action = None
    • Copy to Output Directory=Copy if newer
  • Скопируйте из предыдущего примера контейнер FlowDocument вместе с его содержимым в файл XMLFile1.xaml и добавьте атрибуты пространств имен WPF в дескриптор FlowDocument

Мы создали, так называемый, свободный файл XAML. Свободный файл XAML - это файл со следующими характеристиками:

  • Содержит только XAML (то есть не код C# )
  • Имеет объявление соответствующего пространства имен
  • Имя файла имеет расширение XAML

В нашем случае содержимое файла XMLFile1.xaml должно стать таким

<FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 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>
  • Заполните файл Window1.xaml.cs кодовой части так
using System;using System.Collections.Generic;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes; using System.Windows.Markup;using System.IO; namespace WpfText2{ public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void FlowDocumentScrollViewer_Initialized(object sender, EventArgs e) { documentReader.Document = (FlowDocument)XamlReader. Load(File.OpenRead("XMLFile1.xaml")); // Альтернативный вариант //LoadFlowDocumentScrollViewerWithXAMLFile("XMLFile1.xaml"); } // Альтернативный вариант void LoadFlowDocumentScrollViewerWithXAMLFile(string fileName) { FileStream xamlFile = new FileStream(fileName, FileMode.Open, FileAccess.Read); FlowDocument content = XamlReader.Load(xamlFile) as FlowDocument; documentReader.Document = content; xamlFile.Close(); } }}

Здесь мы свойству Document контейнера просмотра FlowDocumentScrollViewer присваиваем возвращенный классом XamlReader размеченный документ нефиксированного формата.

  • Запустите приложение - получится точно такой же результат, как в предыдущем примере


увеличить изображение

  • Проверьте работу закомментированного альтернативного варианта процедурного кода







Дата добавления: 2015-04-15; просмотров: 1467;


Поиск по сайту:

При помощи поиска вы сможете найти нужную вам информацию.

Поделитесь с друзьями:

Если вам перенёс пользу информационный материал, или помог в учебе – поделитесь этим сайтом с друзьями и знакомыми.
helpiks.org - Хелпикс.Орг - 2014-2024 год. Материал сайта представляется для ознакомительного и учебного использования. | Поддержка
Генерация страницы за: 0.005 сек.