Poma
Poma

Reputation: 8484

How to optimize many same images?

I have a table and many rows contain the same icon <Image Source="{Binding Icon}" /> (there is a set of 6 possible icons). I've noticed that table refresh takes significant amount of time because of those icons (they seem to be regenerated every time). In my program table refreshes very often - once in a 3 sec. Is there a way to optimize this? Maybe declare icon as resource so that it will load only once.

Upvotes: 2

Views: 191

Answers (2)

Phil
Phil

Reputation: 43001

I would suggest ensuring you only create the icon/image once per view model (I'm not keen on using static variables if possible). You should also call Freeze() on the resource for maximum performance.

e.g.

public class MultipleIconsViewModel
{
    private BitmapImage _icon;

    public ImageSource Icon
    {
        get
        {
            if (_icon == null)
            {
                _icon = new BitmapImage(new Uri(@"..\images\myImage.png", UriKind.RelativeOrAbsolute));

                // can't call Freeze() until DownloadCompleted event fires.
                _icon.DownloadCompleted += (sender, args) => ((BitmapImage) sender).Freeze();
            }

            return _icon;
        }
    }
}

Also see this post: WPF image resources which discusses the same problem.

Upvotes: 4

Kent Boogaart
Kent Boogaart

Reputation: 178770

What is the Icon property doing? If it's creating a new ImageSource every time, that would explain the poor performance. If your icon is shared, you could expose it statically (as a singleton) and use the one instance of it.

Upvotes: 2

Related Questions