c# - 如何复制包含溢出内容的 FrameworkElement?

标签 c# wpf xaml bitmap drawing

我正在使用我在 http://brianlagunas.com/wpf-copy-uielement-as-image-to-clipboard/ 找到的一些代码复制呈现的 XAML Treeview。如果内容超出可用高度, TreeView 将配置为滚动。

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);

当我的内容适合客户区时,效果很好:

Treeview when client area is large enough to avoid overflow

但是当内容溢出客户区时就有问题了:

Treeview when client area is too small and overflow occurs

有没有办法无需调整屏幕元素的大小就可以获得整个控件内容?

编辑: 这是 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>

以及将 TreeView 绑定(bind)到按钮命令的按钮:

            <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>

最佳答案

我对您的代码做了一些实验。问题似乎是您正在使用 element.ActualHeightelement.ActualWidth 构造位图,这当然等于 TreeView 控件的当前大小(而不是实际上更长的内容面板),所以这就是您在输出中呈现的内容。

我为解决此问题所做的是将 ScrollViewer.VerticalScrollBarVisibility 设置为 Disabled 用于 TreeView 然后将其包装在 滚动查看器。这将使您的 TreeView 达到它所需要的全高,并且仍然有一个滚动条来滚动它。现在,当您使用 ActualWidth 和 ActualHeight 构建位图时,您会得到一个完整尺寸的位图,并对其进行渲染以获得所需的结果。

关于c# - 如何复制包含溢出内容的 FrameworkElement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37572471/

相关文章:

c# - 字符串未被识别为 Windows Server 2016 上的有效日期时间

c# - 如何将 WPF 控件值绑定(bind)到方法?

wpf - 触发 Button.Click 时的 XAML Binding.UpdateSourceTrigger?

c# - 如何在 C# 代码中使用传递给回调的 C/C++ native 结构

c# - 将按钮的名称传递给文本 block

c# - 注册所有在应用程序启动时实现接口(interface)的类(Web API)

c# - 将 C# 数组传递给 C++ 方法

wpf - 银光下的 Canvas 装订

c# - 如何在xamarin forms android中更改工具栏后退图标

.net - 如何在 XAML 中引用当前对象