C# 以代码而不是XAML呈现UserControl

C# 以代码而不是XAML呈现UserControl,c#,wpf,xaml,user-controls,rendertargetbitmap,C#,Wpf,Xaml,User Controls,Rendertargetbitmap,我想使用RenderTargetBitmap将用户控件渲染到位图,而不必为其编写XAML。当我这样做时,我得到一张空白图像,我是否错过了一个关键步骤 ValTool.Controls.VideoFisheyeOverlayControl vfoc = new Controls.VideoFisheyeOverlayControl(); vfoc.Width = (int)this.VideoContainer.ActualWidth; vfoc.Height = (int)this.VideoC

我想使用
RenderTargetBitmap
将用户控件渲染到位图,而不必为其编写XAML。当我这样做时,我得到一张空白图像,我是否错过了一个关键步骤

ValTool.Controls.VideoFisheyeOverlayControl vfoc = new Controls.VideoFisheyeOverlayControl();
vfoc.Width = (int)this.VideoContainer.ActualWidth;
vfoc.Height = (int)this.VideoContainer.ActualHeight;
vfoc.FieldsOfView=this.FieldsOfView;
vfoc.CountLines = this.CountLines;

vfoc.UpdateLayout();
vfoc.InvalidateVisual();

RenderTargetBitmap visual = new RenderTargetBitmap((int)this.VideoContainer.ActualWidth, (int)this.VideoContainer.ActualHeight, 96, 96, PixelFormats.Pbgra32);
visual.Render(vfoc);
var finalImage = BitmapFrame.Create(visual);
// Encoding the RenderBitmapTarget as a PNG file.
PngBitmapEncoder png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(finalImage));
using (Stream stm = File.Create(@"new.png"))
{
    png.Save(stm);
}

您必须调用并完成布局,而不是UpdateLayout:

var width = VideoContainer.ActualWidth;
var height = VideoContainer.ActualHeight;

vfoc.Measure(new Size(width, height));
vfoc.Arrange(new Rect(0, 0, width, height));
vfoc.InvalidateVisual();