ContentControl + RenderTargetBitmap + empty image ContentControl + RenderTargetBitmap + empty image wpf wpf

ContentControl + RenderTargetBitmap + empty image


Calling element.ApplyTemplate() did the trick.


If someone has similar problems with rendering RenderTargetBitmap (getting white / empty image) items that are in StackPanel you can temporary move them to Grid, then render and put it back in StackPanel

Grid grid = new System.Windows.Controls.Grid() { Background = Brushes.White, Width = iWidth, Height = iHeight };Panel panel = plot.Parent as Panel;if (panel != null){    panel.Children.Remove(plot);    grid.Children.Add(plot);    grid.Measure(new Size(iWidth, iHeight));    grid.Arrange(new Rect(new Size(iWidth, iHeight)));}plot.Measure(new Size(iWidth, iHeight));plot.Arrange(new Rect(new Size(iWidth, iHeight)));plot.ApplyTemplate();plot.UpdateLayout();grid.ApplyTemplate();grid.UpdateLayout();RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(    iWidth,    iHeight,    96, 96, PixelFormats.Pbgra32);renderTargetBitmap.Render(grid);PngBitmapEncoder encoder = new PngBitmapEncoder();encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));MemoryStream memoryStream = new MemoryStream();encoder.Save(memoryStream);bitmap = new System.Drawing.Bitmap(memoryStream);if (panel != null){    grid.Children.Remove(plot);    panel.Children.Add(plot);}plot.Measure(new Size(iWidthBefore, iHeightBefore));plot.Arrange(new Rect(new Size(iWidthBefore, iHeightBefore)));plot.UpdateLayout();


For me, calling element.Arrange() was the missing piece.