How to copy a FrameworkElement element including overflowing content?

I am using the code that I found at http://brianlagunas.com/wpf-copy-uielement-as-image-to-clipboard/ to copy the rendering of the XAML tree. The tree structure is configured to scroll if the content overflows the available height.

const long DPI = 96; FrameworkElement element = (FrameworkElement)param; double height = element.ActualHeight; double width = element.ActualWidth; RenderTargetBitmap bmp = new RenderTargetBitmap((int)Math.Round(width), (int)Math.Round(height), DPI, DPI, PixelFormats.Default); DrawingVisual dv = new DrawingVisual(); using (DrawingContext dc = dv.RenderOpen()) { VisualBrush vb = new VisualBrush(element); dc.DrawRectangle(vb, null, new Rect(new Point(), new Size(width, height))); } bmp.Render(dv); DataObject _data = new DataObject(); _data.SetImage(bmp); 

This works great when my content is placed inside the client area:

Treeview when the client area is large enough to avoid overflow

But this is a problem when the content overflows the client area:

Treeview when client area is too small and overflow occurs

Is there a way to get all the control content without resizing the screen element?

Edit: Here Treeview XAML:

  <TreeView x:Name="ProjectTree" Grid.Row="1" ItemContainerStyle="{StaticResource ShinyTreeView}" HorizontalContentAlignment="Stretch" MouseDoubleClick="TreeView_OnMouseDoubleClick" Style="{StaticResource CodeExplorerTreeViewStyle}" BorderThickness="0,1" VirtualizingPanel.IsVirtualizing="False"> <i:Interaction.Behaviors> <controls:BindableSelectedItemBehavior SelectedItem="{Binding SelectedItem, Mode=TwoWay}" /> </i:Interaction.Behaviors> </TreeView> 

And the button that binds the tree to the button command:

  <Button Command="{Binding CopyResultsCommand}" CommandParameter="{Binding ElementName=ProjectTree}"> <Image Height="16" Source="../../Resources/document-copy.png" /> <Button.ToolTip> <TextBlock Text="{Resx ResxName=Rubberduck.UI.RubberduckUI, Key=CodeExplorer_CopyToolTip}" /> </Button.ToolTip> </Button> 
+7
c # wpf bitmap xaml drawing
source share
1 answer

I experimented a bit with your code. The problem is that you use element.ActualHeight and element.ActualWidth to build a bitmap, which of course is equal to the current size of the TreeView control (and not the content panel, which is actually larger), so what you get visualization at the exit.

What I did to fix the problem was to set ScrollViewer.VerticalScrollBarVisibility to Disabled for TreeView , and then wrap it inside a ScrollViewer . This will make your TreeView full height it requires, and still has a scroll bar to scroll it. Now, when you create a bitmap using ActualWidth and ActualHeight, you get a full-sized bitmap and rendering that gives the desired result.

+1
source share

All Articles