2009-02-02 59 views
42

我可以使用现有的WPF(XAML)控件将其数据绑定并将其转换为可使用WPF XPS文档查看器显示和打印的XPS文档? 如果是这样,怎么样? 如果不是,我应该如何使用XPS/PDF /等在WPF中进行“报告”?将WPF(XAML)控件转换为XPS文档

基本上我想采取一个现有的WPF控件,数据绑定它获得有用的数据,然后使其可打印和可保存为最终用户。理想情况下,文档创建将在内存中完成,除非用户专门保存了文档,否则不会触及磁盘。这是可行的吗?

+0

[http://msdn.microsoft.com/en-us/library/system.windows.xps.visualstoxpsdocument.aspx](http://msdn.microsoft.com/en-us/library/system.windows .xps.visualstoxpsdocument.aspx) – 2009-02-02 05:20:17

回答

61

与不同样品的堆,所有这一切都是令人难以置信的令人费解,并要求使用文档作家,容器,打印队列和打印门票乱搞后其实,我发现埃里克汇文章关于Printing in WPF
简化代码是仅10线长

public void CreateMyWPFControlReport(MyWPFControlDataSource usefulData) 
{ 
    //Set up the WPF Control to be printed 
    MyWPFControl controlToPrint; 
    controlToPrint = new MyWPFControl(); 
    controlToPrint.DataContext = usefulData; 

    FixedDocument fixedDoc = new FixedDocument(); 
    PageContent pageContent = new PageContent(); 
    FixedPage fixedPage = new FixedPage(); 

    //Create first page of document 
    fixedPage.Children.Add(controlToPrint); 
    ((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage); 
    fixedDoc.Pages.Add(pageContent); 
    //Create any other required pages here 

    //View the document 
    documentViewer1.Document = fixedDoc; 
} 

我的样品是相当简单的,它不包括页面大小和方向包含一套完全不同的你所期望的,不工作的问题。 它也不包含任何保存功能,因为MS似乎忘记了在文档查看器中包含保存按钮。

保存功能是相对简单的(并且也为埃里克汇文章)

public void SaveCurrentDocument() 
{ 
// Configure save file dialog box 
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); 
dlg.FileName = "MyReport"; // Default file name 
dlg.DefaultExt = ".xps"; // Default file extension 
dlg.Filter = "XPS Documents (.xps)|*.xps"; // Filter files by extension 

// Show save file dialog box 
Nullable<bool> result = dlg.ShowDialog(); 

// Process save file dialog box results 
if (result == true) 
{ 
    // Save document 
    string filename = dlg.FileName; 

    FixedDocument doc = (FixedDocument)documentViewer1.Document; 
    XpsDocument xpsd = new XpsDocument(filename, FileAccess.ReadWrite); 
    System.Windows.Xps.XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd); 
    xw.Write(doc); 
    xpsd.Close(); 
} 
} 

因此,答案是肯定的,你可以利用现有的WPF(XAML)控制,数据绑定,并把它变成一个XPS文件 - 并不是那么困难。

+1

您能否提供MyWPFControl和MyWPFControlDataSource的定义?没有它们的示例代码是毫无价值的,并且Sinks文章似乎没有包含它们。 – 2009-12-14 21:58:10