Fork me on GitHub

RickTextBox

 

这是的RickTextBox很像其他IDE中的memo,是一个支持多种样式的编辑区。在保存文件时先读取RickTextBox的段落内容,然后再生成一个流文件,保存在指定文件下。加载是一个相反的过程。打印是用PrintDialog来完成打印。

XAML代码:

<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>

CS代码:

   void   SaveRTBContent(Object sender, RoutedEventArgs args)

        {       

            SaveXamlPackage("E:\\test.xaml");

        }

   void LoadRTBContent(Object sender, RoutedEventArgs args)

        {

            LoadXamlPackage("E:\\test.xaml");

        }

        void PrintRTBContent(Object sender, RoutedEventArgs args)

        {

            PrintCommand();

        }

        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();

        }

        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();

            }

        }

        private void PrintCommand()

        {

            PrintDialog pd = new PrintDialog();

            if ((pd.ShowDialog() == true))

            {

                pd.PrintVisual(richTB as Visual, "printing as visual");                pd.PrintDocument((((IDocumentPaginatorSource)richTB.Document).DocumentPaginator), "printing as paginator");

            }

        }

 本文参考msdn组织

posted @ 2007-04-23 23:25  桂素伟  阅读(562)  评论(0编辑  收藏  举报