我能否采用现有的 WPF (XAML) 控件,对其进行数据绑定(bind)并将其转换为可以使用 WPF XPS 文档查看器显示和打印的 XPS 文档? 如果是这样,如何? 如果不是,我应该如何使用 XPS/PDF/等在 WPF 中进行“报告”?
基本上我想采用现有的 WPF 控件,对其进行数据绑定(bind)以将有用的数据输入其中,然后使其可打印并可供最终用户保存。理想情况下,文档创建将在内存中完成,除非用户专门保存文档,否则不会写入磁盘。这可行吗?
最佳答案
实际上,在摆弄了一堆不同的样本之后,所有这些样本都非常复杂并且需要使用文档编写器、容器、打印队列和打印票证,我发现了 Eric Sinks 关于 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 似乎忘记了在文档查看器中包含一个保存按钮。
保存功能相对简单(也是来自 Eric Sinks 的文章)
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) 控件,对其进行数据绑定(bind)并将其转换为 XPS 文档 - 并没有那么困难。
关于c# - 将 WPF (XAML) 控件转换为 XPS 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/502198/