WPF Control to ContextMenu Menu Icon

260 Views Asked by At

Setup

I have a series of drag and drop elements (WPF Controls) on a template. When those template elements are stacked I offer the user the ability to unstack them through the context menu. The context menu items are generated in the behind code in an extension class I created.

Problem

I would like to offer an image of the element as the icon in the context menu, next to the corresponding menu item header. Currently I have tried a series of solutions, none of which work.

Atempted solutions

How can I convert a WPF control into an image?

Get a bitmap image from a Control view

The MenuItem.Icon takes a visual object. Unfortunately when I just hand it my element, which is a visual, it bombs because the element is part of another visual tree.

So I tried cloaning it and then providing it the same DataContext. Which worked, kinda. Without going into to much depth, the size of the element is bound to the datacontext so it's VERY difficult to adjust the size from the behind code without it looking like a giant hack.

Desired outcome

I want to render an image of my WPF control and assign that to the MenuItem.Icon property. Also I need to be able to do this in the behind code.

1

There are 1 best solutions below

1
On

To get an image of a control, you can do using a VisualBrush, with Visual bound to the control. An example of this with transforms (stretching, etc) can be found at MSDN here.