Thursday, April 12, 2012

wpf fixeddocument dynamic data

I am creating FixedDocument and adding pages to it dynamically.

FixedDocument fd = new FixedDocument();   
     FixedPage page1 = new FixedPage();
     page1.Width = visual1.DocumentPaginator.PageSize.Width;
     page1.Height = visual1.DocumentPaginator.PageSize.Height;
     PageContent page1Content = new PageContent();
 private void Pageinit()
     TextBlock tb = new TextBlock();
     tb.Text = "From Data";

This code gives the following error:

"Specified Visual is already a child of another Visual or the root of
a CompositionTarget."

What could be the problem.


It is an easy error to diagnose; an visual can only ever have one parent as otherwise you would have a circular dependency in the VisualTree. Review your code to check if you are using the same visual twice.
If you want the visual to appear in two places simultaneously then you need to duplicate it; if the second use is intentional then you can un-parent visual by removing itself from the parent. e.g. (canvas.Parent.Remove(canvas)).
In the code sample posted I can identify at least one instance of where this would occur and have detailed this below.

You are adding the instance of vCanvas to more than once in your while(loop) block. You need to create a new Canvas for each iteration.
var visual = /* unknown */; var fd = new FixedDocument();    while(loop) { 
    var canvas = PageInit(); 
    var page = new FixedPage(); 
    page.Width = visual.DocumentPaginator.PageSize.Width; 
    page.Height = visual.DocumentPaginator.PageSize.Height; 
    PageContent pageContent = new PageContent(); 
    visual.Pages.Add(pageContent); } 
For the purposes of this example, I will the Canvas in the PageInit().
private Canvas PageInit() { 
    var tb = new TextBlock(); 
    tb.Text = "From Data"; 
    var canvas = new Canvas(); 
    return canvas; } 

No comments:

Post a Comment