title: Printing in Silverlight/Lightswitch using XAML and custom controls
body: <p>I am programming a Silverlight application using Lightswitch. I want to print the data which is displayed on some screens.</p>
  
  <p>I found <a href="http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/3/Printing-With-LightSwitch.aspx" rel="nofollow noreferrer">this tutorial</a> for printing in Silverlight/Lightswitch. It describes how to create a custom control using XAML which can be printed. The control looks like this:</p>
  
  <p><img src="https://i.stack.imgur.com/pnMbr.png" alt="Printing in Lightswitch"></p>
  
  <p>In the background you can see the control how it looks like in the Silverlight application. The control contrains both a button and a grid:</p>
  
  <pre><code>&lt;StackPanel&gt;
      &lt;Button Content="Print" Name="btnPrint" Click="btnPrint_Click" /&gt;
          &lt;Grid x:Name="LayoutRoot"&gt;
              &lt;!-- grid code goes here --&gt;
              &lt;!-- some more code an closing tags --&gt;
  </code></pre>
  
  <p>Using Silverlight's printing API, printing is done like this in the custom control:</p>
  
  <pre><code>PrintDocument printInvoice = new PrintDocument();
  private void btnPrint_Click(object sender, System.Windows.RoutedEventArgs e){   
      printInvoice.PrintPage +=
          new EventHandler&lt;PrintPageEventArgs&gt;(printInvoice_PrintPage);
  }
  
  void printInvoice_PrintPage(object sender, PrintPageEventArgs e){
      e.PageVisual = LayoutRoot;
  }
  </code></pre>
  
  <p>Since <code>e.PageVisual = LayoutRoot</code> is used, we only see the table in the printed output, and not the button. That's okay, but I would like to use a seperate XAML for the print layout. My goal is to just show a button <code>Print</code> on the Silverlight application, and define the print layout in a seperate XAML.</p>
  
  <p>So, I just started to create a second XAML as SilverlightControl and tried to use it:</p>
  
  <pre><code>MyPrintLayout mpl = new MyPrintLayout();
  void printArtikels_PrintPage(object sender, PrintPageEventArgs e){
      e.PageVisual = mpl.LayoutRoot;
  }
  </code></pre>
  
  <p>But I get the error "Das Element ist bereits das untergeordnete Element eines anderen Elements" (english: "The element is already the sub-element of another element"). This error was discussed in <a href="https://stackoverflow.com/questions/5578109/wpf-datagrid-bug-when-toggle-visibility-on-a-column-with-an-image-as-headercont">this question</a> as well, but it does not solve my problem. </p>
  
  <p>When I include <code>MyPrintLayout</code> in the silverlight application it is displayed without a problem (there is only some text in it to test the functionality).</p>
  
  <p>It seems like I am doing this completely wrong. How can I achieve my goal?</p>