Thursday, April 12, 2012

wpf fixeddocument dynamic data

I am creating FixedDocument and adding pages to it dynamically.


FixedDocument fd = new FixedDocument();   
 while(loop)
 {
     Pageint();
     FixedPage page1 = new FixedPage();
     page1.Width = visual1.DocumentPaginator.PageSize.Width;
     page1.Height = visual1.DocumentPaginator.PageSize.Height;
     page1.Children.Add(vCanvas);
 
     PageContent page1Content = new PageContent();
     ((IAddChild)page1Content).AddChild(page1);
     visual1.Pages.Add(page1Content);
 }
 
 private void Pageinit()
 {
     TextBlock tb = new TextBlock();
     tb.Text = "From Data";
     vCanvas.Children.Add(tb);
 }
 


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.



Answer:

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; 
    page.Children.Add(canvas); 
 
    PageContent pageContent = new PageContent(); 
    ((IAddChild)pageContent).AddChild(page); 
    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(); 
    canvas.Children.Add(tb); 
 
    return canvas; } 

No comments:

Post a Comment