打印 UI:指定的视觉对象已经是另一个视觉对象的子项或组合目标的根

本文关键字:视觉 对象 目标 组合 另一个 UI 打印 | 更新日期: 2023-09-27 18:37:27

所以我构建了一个所见即所得的编辑器,允许用户在画布上拖放控件。然后,在按照他们想要的方式安排之后,他们可以打印出模板。

不过,我在可视化树中遇到了一些问题。

XAML

  <Grid>
    <Grid.ColumnDefinitions>
            <ColumnDefinition Width=".2*"/>
            <ColumnDefinition Width=".8*"/>
    </Grid.ColumnDefinitions>
    <StackPanel AllowDrop="False" Background="Gray">
      <!--REMOVED-->
    </StackPanel>
    <Canvas Grid.Column="1" AllowDrop="True" Width="600" Height="800"                 
            Background="White" x:Name="CanvasControl" 
            DataContext="{Binding CanvasVM}" 
            DragEnter="CanvasFlowDocument_DragEnter" 
            DragLeave="CanvasFlowDocument_DragLeave" 
            DragOver="CanvasFlowDocument_DragOver" 
            Drop="CanvasFlowDocument_Drop"/>
  </Grid>

C#

private void PrintCanvas()
{
   //Prompt for print
   PrintDialog pd = new PrintDialog();
   if (pd.ShowDialog()==true)
   {
       //Trying to use flow document for printing because I need to be able to control 
       //how the margins look on the page
       FlowDocument CanvasFlowDocument = new FlowDocument();
       BlockUIContainer buiCont = new BlockUIContainer();   
       //Get the parent of the CanvasControl because I can't pass the CanvasControl to my
       //Printer until it doesn't have a logical visual parent             
       Grid par = (Grid)CanvasControl.Parent;
       par.Children.Remove(CanvasControl);
       //Add Control to Block UI Container for printing
       buiCont.Child = CanvasControl;
       CanvasFlowDocument.Blocks.Add(buiCont);
        //Print the doc
       pd.PrintDocument((CanvasFlowDocument as IDocumentPaginatorSource).DocumentPaginator, "Template");
       //Now, in an attempt to re-add my canvas to the grid so my user can continue to see/manipulate it. I first clear the blocks
       CanvasFlowDocument.Blocks.Clear();
       //I even go as far as setting the Block UI Container child to null
       buiCont.Child = null;
       CanvasControl.UpdateLayout();
       //This is where explosions ensue...
       //The CanvasControl.Parent is null at this point, yet I still get the error below
       par.Children.Add(CanvasControl);
  }          
}

错误:

指定的视觉对象已经是另一个视觉对象的子项或 组成目标

打印 UI:指定的视觉对象已经是另一个视觉对象的子项或组合目标的根

我发现Parent属性可以为 NULL,但组件显然附加到某些视觉对象。在这种情况下,您需要使用 var parentObject = VisualTreeHelper.GetParent(child); ,这将可靠地告诉您视觉父级。您可以简单地使用以下代码片段:

var parentObject = VisualTreeHelper.GetParent(child);
if (parentObject != null)
{
    parentObject.Children.Remove(child);
}