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

丶灬走出姿态 提交于 2019-12-22 08:37:42

问题


I need to store the content of a Window into an image, save it and close the window. If I close the window on the Loaded event the image contains the Window with some items are drawn ok, some others are only half drawn or distorted while others are not on the image.

If I put a timer and close the window after a certain amount of time (something between 250ms and 1sec depending on the complexity of the window) the images are all ok.

Looks like the window needs some time to completely render itself. Is there a way to know when this rendering has been done to avoid using a Timer and closing the window when we know it has completed its rendering?

Thanks.


回答1:


I think you are looking for the ContentRendered event




回答2:


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;
        }



回答3:


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.



来源:https://stackoverflow.com/questions/10330446/how-to-know-when-a-control-or-window-has-been-rendered-drawn-in-wpf

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