方法 : RichTextBox コンテンツを保存、読み込み、および印刷する
更新 : 2007 年 11 月
RichTextBox のコンテンツをファイルに保存し、そのコンテンツを再び RichTextBox に読み込み、そのコンテンツを印刷する方法を次の例に示します。
使用例
以下は、この例のマークアップです。
<Page xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.SaveLoadPrintRTB" >
<StackPanel>
<RichTextBox Name="richTB">
<FlowDocument>
<Paragraph>
<Run>Paragraph 1</Run>
</Paragraph>
</FlowDocument>
</RichTextBox>
<Button Click="SaveRTBContent">Save RTB Content</Button>
<Button Click="LoadRTBContent">Load RTB Content</Button>
<Button Click="PrintRTBContent">Print RTB Content</Button>
</StackPanel>
</Page>
以下は、この例の分離コードです。
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
namespace SDKSample
{
public partial class SaveLoadPrintRTB : Page
{
// Handle "Save RichTextBox Content" button click.
void SaveRTBContent(Object sender, RoutedEventArgs args)
{
// Send an arbitrary URL and file name string specifying
// the location to save the XAML in.
SaveXamlPackage("C:\\test.xaml");
}
// Handle "Load RichTextBox Content" button click.
void LoadRTBContent(Object sender, RoutedEventArgs args)
{
// Send URL string specifying what file to retrieve XAML
// from to load into the RichTextBox.
LoadXamlPackage("C:\\test.xaml");
}
// Handle "Print RichTextBox Content" button click.
void PrintRTBContent(Object sender, RoutedEventArgs args)
{
PrintCommand();
}
// Save XAML in RichTextBox to a file specified by _fileName
void SaveXamlPackage(string _fileName)
{
TextRange range;
FileStream fStream;
range = new TextRange(richTB.Document.ContentStart, richTB.Document.ContentEnd);
fStream = new FileStream(_fileName, FileMode.Create);
range.Save(fStream, DataFormats.XamlPackage);
fStream.Close();
}
// Load XAML into RichTextBox from a file specified by _fileName
void LoadXamlPackage(string _fileName)
{
TextRange range;
FileStream fStream;
if (File.Exists(_fileName))
{
range = new TextRange(richTB.Document.ContentStart, richTB.Document.ContentEnd);
fStream = new FileStream(_fileName, FileMode.OpenOrCreate);
range.Load(fStream, DataFormats.XamlPackage);
fStream.Close();
}
}
// Print RichTextBox content
private void PrintCommand()
{
PrintDialog pd = new PrintDialog();
if ((pd.ShowDialog() == true))
{
//use either one of the below
pd.PrintVisual(richTB as Visual, "printing as visual");
pd.PrintDocument((((IDocumentPaginatorSource)richTB.Document).DocumentPaginator), "printing as paginator");
}
}
}
}