我正在尝试在WPF应用程序中打印WindowsFormsHost。 如果WindowsFormsHost对象是由xaml创建的,它打印正常,但如果我在代码中创建WindowsFormsHost,它会打印一个空页。
如何在代码中创建WindowsFormsHost对象以使其打印输出?
以下是简化但有效的代码:
PrintDialog dialog = new PrintDialog();
if (dialog.ShowDialog() == true)
{
System.Windows.Forms.TextBox ctrl = new System.Windows.Forms.TextBox();
ctrl.Text = "Test";
ctrl.BackColor = System.Drawing.Color.Red;
#if RUNTIME
WindowsFormsHost wfh = new WindowsFormsHost();
wfh.Child = ctrl;
FrameworkElement visual = wfh;
#else
WFHostTest.Child = ctrl;
FrameworkElement visual = WFHostTest;
#endif
visual.Margin = new Thickness(0, 0, 0, 0);
visual.Measure(new Size(dialog.PrintableAreaWidth, dialog.PrintableAreaHeight));
visual.Arrange(new Rect(0, 0, dialog.PrintableAreaWidth, dialog.PrintableAreaHeight));
visual.UpdateLayout();
dialog.PrintVisual(visual, "Test");
}
此代码仅在未定义RUNTIME时打印TextBox。 如果定义了RUNTIME,则会打印一个空页面。 WFHostTest在xaml中定义为
<WindowsFormsHost Grid.Column="1" Grid.Row="2" Name="WFHostTest" />