0

I am building a test report in XAML that needs to be exported into an XPS file. This is the code I have below, however I'm running into an "Specified element is already the logical child of another element. Disconnect it first." error when running fixedPage.Children.Add(TestReportXAML); TestReportXAML is the name of my Grid in the Xaml.cs file

FixedDocument fixedDoc = new FixedDocument();
PageContent pageContent = new PageContent();
FixedPage fixedPage = new FixedPage();

fixedDoc.DocumentPaginator.PageSize = new Size(96 * 11, 96 * 8.5); // LANDSCAPE
fixedPage.Width = 11 * 96;
fixedPage.Height = 8.5 * 96;

fixedPage.Children.Add(TestReportXAML);
((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage);
fixedDoc.Pages.Add(pageContent);

XpsDocument xpsDoc = new XpsDocument(pathFileNameXPS, FileAccess.ReadWrite);
XpsDocumentWriter xpsWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc);
xpsWriter.Write(fixedDoc);
xpsDoc.Close();

Initially I had this set of code that worked, however the problem with this is that my XAML gets saved in portrait mode. I don't know if there's a proper way to make this landscape so I'm trying to use a fixed document to convert the XAML orientation before exporting it to XPS.

XpsDocument xpsDoc = new XpsDocument(pathFileNameXPS, FileAccess.ReadWrite);
XpsDocumentWriter xpsWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc);
xpsWriter.Write(TestReportXAML);
xpsDoc.Close();

I am a new developer and new to XAML/WPF, appreciate if things could be explained in less technical terms. Thanks

Sqwirl
  • 21
  • 6
  • Technically, XAML doesn't have an orientation - it's a text file declaring objects, their properties, and how they are related. I think you must have meant the XPS is in the wrong orientation (I guess, idk what XPS is). – Steve Dec 16 '22 at 23:35
  • How is `TestReportXaml` actually defined/loaded? The problem is within this xaml file or how it was loaded, not in the code where you're using it. It must have a parent defined, otherwise you wouldn't get that error. Find that. Debug your program and inspect your object. – Steve Dec 16 '22 at 23:37
  • @Steve Hey Steve, yes, I did mean the conversion to XPS is in wrong orientation. XPS is just a file extension like PDF. `TestReportXaml` is defined in the main of my Xaml. My Xaml looks pretty much like this structure: ` ` – Sqwirl Dec 17 '22 at 02:23
  • Ok, so let's see how you initialize the variable TestReportXAML. What is it's type? How do you get that variable? – Steve Dec 17 '22 at 17:04
  • @Steve Not sure what you mean by initialize in this scenario but the only two instances where I use `TestReportXAML` is when I bind it to the **Name** property of my grid and when I try to use it in the code of the original post. The type is being recognized as a **Grid** – Sqwirl Dec 19 '22 at 13:24

0 Answers0