为什么子画布上的项目不使用WPF打印

本文关键字:WPF 打印 项目 为什么 | 更新日期: 2023-09-27 17:59:20

试图构造一个页面以便打印。作为一个例子,我有以下内容——主要基于此http://tech.pro/tutorial/881/printing-in-wpf:

 PrintDialog printDialog = new PrintDialog();
 printDialog.PageRangeSelection = PageRangeSelection.AllPages;
 printDialog.UserPageRangeEnabled = true;
 var doPrint = printDialog.ShowDialog();
 if (doPrint == true)
 {        
            StackPanel myPanel = new StackPanel();
            myPanel.Margin = new Thickness(15);
            Image myImage = new Image();
            myImage.Width = 128;
            myImage.Stretch = Stretch.Uniform;
            myImage.Source = new BitmapImage(new Uri("C:''Tree.jpg", UriKind.Absolute));
            myPanel.Children.Add(myImage);
            TextBlock myBlock = new TextBlock();
            myBlock.Text = "A Great Image.";
            myBlock.TextAlignment = TextAlignment.Center;
            myPanel.Children.Add(myBlock);
            Canvas canvasL = new Canvas();
            canvasL.Width = 300;
            canvasL.Height = 300;
            canvasL.Background = Brushes.LightSteelBlue;
            myPanel.Children.Add(canvasL);
            Line l = new Line();
            l.X1 = 0;
            l.Y1 = 0;
            l.Y1 = 10000;
            l.Y2 = 10000;
            l.Stroke = Brushes.Black;
            l.StrokeThickness = 5;
            canvasL.Children.Add(l);
            myPanel.Measure(new Size(printDialog.PrintableAreaWidth,
              printDialog.PrintableAreaHeight));
            myPanel.Arrange(new Rect(new Point(0, 0),
              myPanel.DesiredSize));
            printDialog.PrintVisual(myPanel, "A Great Image.");
}

如图所示。文本显示。画布显示为一个钴蓝色的正方形,但这条线却看不见。

什么东西?

为什么子画布上的项目不使用WPF打印

您需要使用附加的属性设置子对象在画布上的位置。例如

l.SetValue(Canvas.TopProperty, 10d);
l.SetValue(Canvas.LeftProperty, 10d);
l.SetValue(Canvas.RightProperty, 100d);
l.SetValue(Canvas.BottomProperty, 100d);

Agh。布偶。

因此,这个琐碎的例子被窃听了,因为它设置了两次Y1。修复它,它就起作用了。

我更复杂的情况是使用ActualWidth,打印时为0(与在主UI中不同),因此没有显示任何内容。