I am creating FixedDocument
and adding pages to it dynamically.
public partial class Window1 : Window
{
FixedDocument fd = new FixedDocument();
TextBlock page1Text = new TextBlock();
public Window1()
{
InitializeComponent();
}
private void Print_Click(object sender, RoutedEventArgs e)
{
PrintDialog pd = new PrintDialog();
fd.DocumentPaginator.PageSize = new Size(pd.PrintableAreaWidth, pd.PrintableAreaHeight);
for (int i = 0; i <= 5; i++)
{
FixedPage page1 = new FixedPage();
page1.Width = fd.DocumentPaginator.PageSize.Width;
page1.Height = fd.DocumentPaginator.PageSize.Height;
pages();
page1.Children.Add(page1Text);
PageContent page1Content = new PageContent();
((IAddChild)page1Content).AddChild(page1);
fd.Pages.Add(page1Content);
}
DocumentViewer dr = new DocumentViewer();
dr.Height = 700;
dr.Document =fd;
stack.Children.Add(dr);
}
private void pages()
{
page1Text.Text = "This is a test";
page1Text.FontSize = 40;
page1Text.Margin = new Thickness(96);
}
}
The code is still giving error that page1content is a child of another parent.
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 yourwhile(loop)
block. You need to create a newCanvas
for each iteration.For the purposes of this example, I will the
Canvas
in thePageInit()
.I did it. The solution is as follows
You can skip the canvas. It is requirment of my project so I was trying it.