为什么需要在打印之前调用Dispatcher.BeginInvoke()来使视觉对象正确绑定? [英] Why do I need to call Dispatcher.BeginInvoke() to allow a visual to properly bind before printing?

查看:230
本文介绍了为什么需要在打印之前调用Dispatcher.BeginInvoke()来使视觉对象正确绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个固定尺寸为850x1100的UserControl,可以为我提供与信件尺寸的纸相同的纵横比。我在 Viewbox 的窗口中显示此内容,它的行为很像打印预览。该控件继承了我窗口的DataContext,并且当它显示在屏幕上时,所有绑定都起作用,而且看起来很棒。

I have a UserControl with a fixed size of 850x1100 to give me the same aspect ratio as a letter-sized piece of paper. I display this in my window inside a Viewbox, and it acts much like a print preview. The control inherits my window's DataContext, and when it's displayed on the screen, all the bindings work and it looks wonderful.

我已经在窗口代码中编写了以下代码后面(我认为这是完全面向视图的操作)尝试进行打印。如果我按编写的方式执行此代码,则该控件会打印,但似乎没有绑定数据。

I've written the code below in my window's code behind (I feel it's a totally view-oriented operation) to attempt to print it. If I execute this code as written, the control prints, but does not appear to be data bound.

private void PrintButton_Click(object sender, RoutedEventArgs e) {
    var dlg = new PrintDialog();
    var result = dlg.ShowDialog();
    if (result == null || !(bool)result)
        return;

    var page = new InspectionFormPrintView { DataContext = this.DataContext };

    page.Measure(new Size(dlg.PrintableAreaWidth, dlg.PrintableAreaHeight));
    page.Arrange(new Rect(new Point(0, 0), page.DesiredSize));

    dlg.PrintVisual(page, "Inspection Form");
}

如果我将该方法的最后一行修改为

If I modify the last line in that method to

Dispatcher.BeginInvoke(new Action(() => dlg.PrintVisual(page, "Inspection Form")), DispatcherPriority.ApplicationIdle, null);

它将很好打印。为什么会这样?

it will print just fine. Why is this?

推荐答案

正如LPL在评论中提到的,这是必需的,因为WPF需要执行所有数据绑定。 。由于WPF操作在 Dispatcher 上排队,因此您需要在 DispatcherPriority.DataBind 之后排队完成打印操作。因此,使用 DispatcherPriority.Render 或更低版本调用 BeginInvoke 将给WPF时间来处理控件上的绑定,因此它们出现在您的打印输出中。

As mentioned by LPL in the comments, this is required because WPF needs to perform the all the data bindings. Since WPF operations are queued on the Dispatcher, you need to queue your print operation to complete after DispatcherPriority.DataBind. Therefore, calling BeginInvoke with DispatcherPriority.Render or lower will give WPF time to process the bindings on the control, so they show up in your printed output.

这篇关于为什么需要在打印之前调用Dispatcher.BeginInvoke()来使视觉对象正确绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆