2

我们从 XPS 文档中加载 FixedPage 对象,处理并显示它。以下代码从 Package 中加载 FixedPage:

        FixedPage fp = null;
        Package package;   // xps package
        Uri packageUri;    // uri of the package in the package store
        Uri fixedPageUri;  // uri of the fixed page
        Dispatcher _mainDispatcher // reference to the main dispatcher, passed to this function
                                   // this function runs in a different thread

        // get the fixed page stream
        Stream stream = package.GetPart(fixedPageUri).GetStream();

        // create a parser context to help XamlReader with the resources used in the page
        ParserContext pc = new ParserContext();
        pc.BaseUri = PackUriHelper.Create(packageUri, fixedPageUri);

        _mainDispatcher.BeginInvoke(
                    new UIRenderDelegate(delegate()
                    {
                        // this line takes its sweet time
                        fp = XamlReader.Load(stream, pc) as FixedPage;
                        stream.Dispose();
                    }), null).Wait();                       


        // return the created fixed page;

但是,该 XamlReader.Load() 调用需要很长时间(尤其是对于复杂的 FixedPages)并且有时会阻塞 UI。我们可以在另一个线程中使用它自己的 Dispatcher 执行此操作,但由于 FixedPage 类不是可自由处理的,因此主 UI 线程不能使用它。

有没有解决的办法?现在我们被困在使用 RenderTargetBitmap 将 FixedPages 渲染为图像,因为 BitmapSource 是 Freezable。

4

1 回答 1

-1

首先将 xaml 加载到内存流中,然后将内存流传递给 UI 线程。在 UI 线程上解析内存流。这样您就可以在后台线程上执行慢速文件 IO。只有流的内存解析(使用 XamlReader.Load)会在 UI 线程上完成。

这篇文章解释了如何做到这一点。

于 2010-02-25T13:31:57.393 回答