0

I'm caching Views in XAML in order to improve performance (don't need to load the controls again). Does this make sense / improve performance of loading controls?

Problem is, although I'm caching / loading the same thing, it seems when I use the Cached View, it has a different appearance. I think it's not using the ItemTemplateSelector properly.

    var stringKey = GetMIVMString(mivm);
    if (_MyCachedView.ContainsKey(stringKey))
    {
        MainView.Content = _MyCachedView[stringKey];
    }

else
{
    var view = new MyInnerView() { DataContext = mivm };
    MainView.Content = view;

    var itemToCache = MainView.Content as MyInnerView;
    if (itemToCache != null)
    {
        _MyCachedView.Add(stringKey, itemToCache);
    }
}

Thanks!

Water
  • 1,114
  • 1
  • 15
  • 31

1 Answers1

1

Does this make sense / improve performance of loading controls?

Yes, it does make sense, however there are a few things to consider with this.

Probably the most important thing is memory management. You need to consider how much memory you will be using when caching your views.

Picture the scene:

You have a Window, where the DataContext is a View Model which has loaded 1000 records from a database.

Now, when you cache this view, those records will still be in memory, even though they are not being used, eating up resources that would otherwise be used somewhere else. This isn't a massive problem, as computers these days have plenty of memory. However, you must think about how you are going to handle this problem.

My suggestion would be to free up any resources when you close the view. Effectively do a Dispose, without actually disposing the view model entirely. Once the view is relevant again, perform the setup (load the data) on the view model.

it has a different appearance. I think it's not using the ItemTemplateSelector properly.

Consider looking at Sheridan's View Navigation Approach to define a DataTemplate for your View Models.

Community
  • 1
  • 1
Mike Eason
  • 9,525
  • 2
  • 38
  • 63
  • Thanks Mike. I noticed a huge difference in loading when loading from cache and creating a new instance of the view. This is a view that is displayed quite frequently. Problem is, when I load from cache, and user edits or does something from the view, the cached view values also changes. On second load from the cache, the view is not 'clean' anymore and has values from the previous entry. Do you think there is an easy way to get around this? – Water Jun 19 '15 at 16:58