Introduction

The follwoing code sample completed the work of saving RichTextBoxcontent in to XPS file format in MVVM. for that i have taken one RichTextBox and one Button Control in the main window.

In the Delegate Command of Button i have created the object of Print Dialog and in the print method of Print Dialog passed the FlowDocument of RichTextbox. See the bellow code for mere clarification.

XAML Code

<window x:class="PrintingRichTextBoxContent.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" title="MainWindow" height="755"

width="702" initialized="Window_Initialized_1">

<Grid HorizontalAlignment="Left" Height="725" VerticalAlignment="Top" Width="694">

<Button Content="Print" HorizontalAlignment="Left" Margin="307,693,0,0" VerticalAlignment="Top" Width="75" Name="btnPrint" Command="{Binding OpenDialogCommand}" CommandParameter="{Binding ElementName=txtPrintText, Path=Document}"/>

<RichTextBox HorizontalAlignment="Left" Height="678" Margin="10,10,0,0" VerticalAlignment="Top" Width="674" Name="txtPrintText" >

</RichTextBox>

</Grid>

</window>

View Model Code

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Microsoft.Practices.Prism.Commands;

using System.Windows.Controls;

using System.ComponentModel;

using System.Printing;

using System.Windows.Documents;

namespace PrintingRichTextBoxContent

{

public class MainWindowViewModel

{

public DelegateCommand<object> OpenDialogCommand { get; set; }

public MainWindowViewModel()

{

this.OpenDialogCommand = new DelegateCommand<object>(OpenDialogCommand_Excute);

}

private void OpenDialogCommand_Excute(object arg)

{

PrintDialog PD = new PrintDialog();

if (PD.ShowDialog() == true)

PD.PrintDocument(((IDocumentPaginatorSource)arg).DocumentPaginator, "abc");

}

}

}