强制加载流文档

本文关键字:文档 加载 | 更新日期: 2023-09-27 18:37:18

我正在尝试打印出用户正在查看的FlowDocument。 我编写了一个例程来创建原始文档的副本,以便更改(来自 PrintDialog)不会反映到 DocumentViewer 中。

不幸的是,我的副本似乎丢失了绑定到其字段的所有信息。 我尝试重置 DataContext,但副本的 IsLoaded 属性仍然返回 false,导致我相信绑定没有发生。

有什么想法吗?

以下是我用来复制文档的代码:

private static void AddDocument(FlowDocument from, FlowDocument to)
{
    TextRange tr = new TextRange(from.ContentStart, from.ContentEnd);
    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
    {
        TextRange tr2 = null;
        System.Windows.Markup.XamlWriter.Save(tr, ms);
        tr.Save(ms, DataFormats.XamlPackage, true);
        tr2 = new TextRange(to.ContentEnd, to.ContentEnd);
        tr2.Load(ms, DataFormats.XamlPackage);
    }
}

这是我用来打印文档的代码:

public static void PrintFlowDocument(FlowDocument fd, string title)
{
    PrintDialog pd = new PrintDialog();
    IDocumentPaginatorSource idps = null;
    FlowDocument flowDoc = new FlowDocument();
    AddDocument(fd, flowDoc);
    flowDoc.DataContext = fd.DataContext;
    flowDoc.PageHeight = pd.PrintableAreaHeight;
    flowDoc.PageWidth = pd.PrintableAreaWidth;
    flowDoc.PagePadding = new Thickness(50);
    flowDoc.ColumnGap = 0;
    flowDoc.ColumnWidth = pd.PrintableAreaWidth;

    idps = flowDoc;
    if (pd.ShowDialog() == true)
    {
        pd.PrintDocument(idps.DocumentPaginator, title);
    }
}

提前致谢,
桑尼

强制加载流文档

注意到这一行的一些问题了吗?

tr2 = new TextRange(to.ContentEnd, to.ContentEnd);

我遇到了类似的问题,发现强制将文档创建强制到后台线程使绑定有机会触发。否则,它不会在 UI 线程上发生。

因此,如果您的复制文档方法是一个函数,它将是这样的:

            Dim flowDoc As FlowDocument = 
                DirectCast(<ViewInstance>.UIDispatcher.Invoke(Function() 
                               AddFlowDocument(fd),
                               Windows.Threading.DispatcherPriority.Background), 
                           FlowDocument)