Run throguh visual tree and set all Images to null

百般思念 提交于 2019-12-02 19:30:41

问题


I saw tons of threads with memory leaking while using images. So, is it a good idea just to have a general function, some kind of own GC, which would run at NavigatingFrom, find all images (even in templates of virtualized lists) and set them to null?


回答1:


Here is an helper to iterate throught all the images of your page:

public IEnumerable<Image> GetAllImage(DependencyObject root)
    {
        var count = VisualTreeHelper.GetChildrenCount(parentElement);


        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(parentElement, i);
            if (child is Image)
            {
                yield return (Image)child;
            }
            foreach (var image in GetAllImage(child))
            {
                yield return image;
            }

        }
    }

You can just call it with the root of your page as parameter and it should return all the images to you.



来源:https://stackoverflow.com/questions/18886640/run-throguh-visual-tree-and-set-all-images-to-null

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