从DWG到XAML (III)2012-06-07 博客园 Jeffrey Sun.NET中的 XPS Packaging类库及一个DWFx Packaging类库的实现DocumentViewer其实复杂的事情原本可以很简单. 你想要的那个轮子, 也许别人早就为你造好了. 在这里也是如此. 比如全部你想要的, 就是在你的系 统前端可以直接查看DWG文件, 那么全部需要做的, 仅仅是简单的从DWG导出为DWFx文件, 然后使用WPF的DocumentViewer控件打开这个文件 就可以了. 这个示例程序可以从这里获取.XAML1. <DocumentViewer Name="docViewer" />Code-Behind : Load DWFx
1. XpsDocument xpsDocument = null;
2.
3. if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
4. {
5. // If there"s an existing document open, close it.
6. if (xpsDocument != null)
7. xpsDocument.Close();
8.
9. // Create an XpsDocument for the file specified by the user.
10. try
11. {
12. xpsDocument = new
13. XpsDocument(dlg.FileName, System.IO.FileAccess.Read);
14. }
15. catch (UnauthorizedAccessException)
16. {
17. System.Windows.MessageBox.Show(
18. String.Format("Unable to access {0}", dlg.FileName ) );
19. return;
20. }
21.
22. // For optimal performance the XPS document should be remain
23. // open while its FixedDocumentSequence is active in the
24. // DocumentViewer control. When the XPS document is opened
25. // with the XpsDocument constructor ("new XpsDocument" above) a
26. // reference to it is automatically added to the PackageStore.
27. // The PackStore is a static application collection that contains
28. // a reference to each open package along the package"s URI as
29. // a key. Adding a reference of the XPS package to the
30. // PackageStore keeps the package open and avoids repeated opens
31. // and closes while the document content is being accessed by
32. // DocumentViewer control. The XpsDocument.Dispose() method
33. // automatically removes the package from the PackageStore after
34. // the document is removed from the DocumentViewer control and
35. // is no longer in use.
36. docViewer.Document = xpsDocument.GetFixedDocumentSequence();
DocumentViewer是 WPF专为呈现XPS文件内容准备的控件. 它所呈现的内容叫做FixedDocument, 这完全符合XPS的标准. 我们的DWFx格 式文件是与XPS兼容的, 所以也可以被DocumentViewer直接载入和显示.我们用DocumentViewer直接打开一个DWFx文件并仔细对比, 你会发 现它所呈现出来的内容和在AutoCAD中精确地相同.