tags:

views:

208

answers:

2

I need to make areas of XAML printable and so have make this button handler:

private void Button_Click_Print(object sender, RoutedEventArgs e)
{
    Customer.PrintReport(PrintableArea);
}

And in PrintReport I pack the frameworkelement into other elements in order to print it in a slightly different way than it is on the screen, like this:

public void PrintReport(FrameworkElement fwe)
{
    StackPanel sp = new StackPanel();
    sp.Children.Add(fwe);
    TextBlock tb = new TextBlock();
    tb.Text = "hello";
    sp.Children.Add(tb);

    PrintDialog dialog = new PrintDialog();
    if (dialog.ShowDialog() == true)
    { 
        dialog.PrintVisual(sp, "Print job"); 
    }
}

But the above gives me the following error:

Specified element is already the logical child of another element. Disconnect it first.

Is there an easy way to clone the FrameworkElement so that I can manipulate the copy, print it, and then forget about it, leaving the original element in the XAML being displayed on the screen intact?

Something like this I would imagine:

FrameworkElement fwe2 = FrameworkElement.Clone(fwe); //pseudo-code
A: 

Hi Edward,

I'm sure there should be easy way to do the copy (other than detaching from parent, printing and attaching back). For example you could try XamlWriter to write xaml, and then read it back via XamlReader. But I suspect there may be some binding and layout errors this way.

Instead I would try to use WriteableBitmap to take a snapshot of printable area and print it. This way you create raster and loose vector, but I'm not good enough in printing to say if it's good or bad. Anyway you could try and check :).

Cheers, Anvaka.

Anvaka
A: 

This article shows how to clone a DependencyObject without using XamlWriter. It's not the prettiest solution, but it looks like it works.

SwDevMan81