c# - 在它的 "taking a screenshot"之前等待 UI 重绘

标签 c# .net wpf

挑战

我正在尝试创建一个可以在 PDF 文档的页面上绘制卡片的窗口。

这个想法是接收一个集合(应该在卡片上绘制的项目),然后遍历它们,并且对于每个项目,将它加载到一个UniformGrid (给人以真实卡片的印象),捕获屏幕图像并将其绘制到 PDF 文档的页面上。

到目前为止一切顺利。

我尝试过的(部分成功的)

这是我尝试过的:

(以下代码被添加到窗口的 Loaded 事件处理程序中)

PdfDocument document = new PdfDocument();

// This is just an example
int[][] items = new int[10][];

// Fill the matrix

foreach (int[] array in items)
{
    Dispatcher.Invoke(() =>
    {
        // uGrid is an UniformGrid
        uGrid.Children.Clear();

        foreach (int id in array)
        {
            Border child = null;

            // Create child element and add it to the Uniform Grid

            uGrid.Children.Add(child);
        }
    });

    Dispatcher.Invoke(new Action(() =>
    {
        // Draws an image of 'this' to the PDFDocument 'document'
        PdfHelper.DrawPictureOfControlToPdf(document, this);

        // DispatcherPriority.ContextIdle here is responsible for executing the DrawPicture method only after the uGrid has been redrawed
    }), DispatcherPriority.ContextIdle, null);

}

// This will save the PDF on your documents folder
document.Save(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyTestPDF.pdf"));

可以找到完整(但我保证非常简短)的工作示例 on my GitHub

此外,可以找到生成的 PDF(调试时和不调试时 - 请参阅下面的问题)here

问题

上面的代码在 Debug模式下运行良好。

  • 调试时:代码运行无误,创建的 PDF 页数正确,卡片正确绘制。

  • 如果不是:代码运行无误,创建的 PDF 具有正确的页数,但未在其上绘制卡片。


我认为导致问题的原因是以下代码段中的 DispatcherPriority.ContextIdle:

Dispatcher.Invoke(new Action(() =>
{
    PdfHelper.DrawPictureOfControlToPdf(document, this);

}), DispatcherPriority.ContextIdle, null);

它应该表明 Action 必须仅在 UniformGrid 完成重绘时运行(或者更准确地说是在 Dispatcher 处理它之后)。但显然这只适用于 Debug模式。

有人知道怎么解决吗?

如果没有,有没有我没有想到的替代方案?

@编辑

我认为这不重要,但我正在使用 PDFSharp生成/处理 PDF

最佳答案

删除代码中的所有Dispatcher.Invoke(它们在这里没有做任何好事),然后调用

this.UpdateLayout();

在调用 PdfHelper.DrawPictureOfControlToPdf(document, this); 之前强制重绘当前控件。

关于c# - 在它的 "taking a screenshot"之前等待 UI 重绘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47640316/

相关文章:

asp.net - 无法识别的配置部分

c# - 使用 WPF/MVVM 在运行时动态更改 UserControl 内容

c# - 在 Windows 窗体中制作 WPF 渐变

c# - 在 ASP.NET MVC 中,如何使用 Html.ActionLink 生成重复名称 ('?v=1&v=2&v=3' ) 查询字符串

c# - 如何在 C# (Visual Studio) 中获取 IronScheme 函数返回值

c# - 如何在 int 列表中找到满足某些条件的项目的索引?

c# - WPF 用户控件库中的打包字符串

c# - .NET 中是否有线程锁的任何低级别度量/日志记录?

wpf - MVVM 中的事件绑定(bind)

c# - 获取坐标边界框,忽略边缘位置