How to know when a control (or window) has been rendered (drawn) in WPF?

冷暖自知 提交于 2019-12-05 16:07:05

I think you are looking for the ContentRendered event

I had the similar problem in the application I am working, I solved it by using following code, try it and let me know if it helps.

 using (new HwndSource(new HwndSourceParameters())
                   {
                       RootVisual =
                           (VisualTreeHelper.GetParent(objToBeRendered) == null
                                ? objToBeRendered
                                : null)
                   })
        {
            // Flush the dispatcher queue
            objToBeRendered.Dispatcher.Invoke(DispatcherPriority.SystemIdle, new Action(() => { }));

            var renderBitmap = new RenderTargetBitmap(requiredWidth, requiredHeight,
                                                      96d*requiredWidth/actualWidth, 96d*requiredHeight/actualHeight,
                                                      PixelFormats.Default);

            renderBitmap.Render(objToBeRendered);
            renderBitmap.Freeze();                

            return renderBitmap;
        }

I used the method on SizeChanged.

public partial class MyUserControl: UserControl
{

    public MyUserControl()
    {
        InitializeComponent();
        SizeChanged += UserControl_DoOnce; //register
    }

    private void UserControl_DoOnce(object sender, SizeChangedEventArgs e)
    {
        if (ActualHeight > 0)//Once the object has size, it has been rendered.
        {
              SizeChanged -= UserControl_DoOnce; //Unregister so only done once
        }
    }
}

This is the only method that I found to work reliably from the control without referencing the Window.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!