How to create an image of a WPF UserControl at run

2020-02-01 04:56发布

问题:

I've created a WPF application which has a Canvas on which I place UserControls which are moveable and resizeable by the user (just like a Windows-Window). Now I have detected that this can be very slow on older PC's which is a problem.

As a solution I thought about generating a graphic showing the UserControl and show this while resizing/dragging the Control, to prevent WPF from recalculating all Elements permanently. The only problem is that I have no idea how to generate this image.

Is there perhaps something like a function which does this in .Net? Or how could I do this on my own?

回答1:

You can render a WPF control to a bitmap using RenderTargetBitmap, then this image can be copied to the clipboard, saved to a file, or used as part of your GUI

Check out Get a bitmap image from a Control view

Beware with this that you can hit problems when parts of the control you are trying to render are not visible (within a scroll viewer perhaps)



回答2:

WPF applications really do require some fairly serious grunt; particularly in the graphics department and benefit greatly from having a decent video card present in the system. Even then the performance of WPF apps (if not carefully constructed) can leave much to be desired...

That said, you could feasibly use FixedDocument to rasterise a UserControl, and then convert this into a GIF/JPG/PNG and put this in place of the control being resized... however I would expect that process itself to be as slow or slower than your current observed performance issues.