Search code examples
wpfperformancelazy-loadingcollectionviewsourcedeferred-loading

Lazy/deferred loading of a CollectionViewSource?


When you create a CollectionViewSource in the Resources section, is the set Source loaded when the resources are initalized (i.e. when the Resources holder is inited) or when data is bound?

Is there a xamly way to make a CollectionViewSource lazy-load? deferred-load? explicit-load?


Solution

  • The answer is, that the CollectionViewSource does not initialize its Source property as long as not requested!

    Here is my test example:

    <Window 
        x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:src="clr-namespace:WpfApplication2">
      <Window.Resources>
        <CollectionViewSource x:Key="mySource">
          <CollectionViewSource.Source>
            <src:Collection />
          </CollectionViewSource.Source>
        </CollectionViewSource>
      </Window.Resources>
      <!--ListView ItemsSource="{Binding Source={StaticResource mySource}}"/-->
    </Window>
    

    Imports System.Collections.ObjectModel
    Imports System.ComponentModel
    
    Public Class Collection : Inherits ObservableCollection(Of String)
      Public Sub New()
        If Not DesignerProperties.GetIsInDesignMode(New DependencyObject) Then End
    
        For i = 1 To 10
          Add("Item " & i)
        Next
      End Sub
    End Class
    

    Result: the project shuts-down only when the ListView is uncommented.