How to: Show large amounts of data in WPF using UI Virtualization

Today I saw a question in the Composite WPF forum that was asking for a way to show 40000 entries in a WPF ListView, with Databinding, in a fast manner since the user's application was taking to long to load all the employees.

Therefore, I started doing some digging and found out that UI Virtualization could do the trick. This basically means that the process of showing a specific item in an ItemsControl is postponed until the item is within visibility range.

The ListView and ListBox controls have UI Virtualization enabled by default when their items are bound to data. In other ItemsControls, like TreeViews, it can be enabled using the VirtualizingStackPanel.IsVirtualizing attached property.

In the .NET Framework 3.5 SP1 an addition was made to improve UI Virtualization which is Container Recycling. You can read more about UI Virtualization and Container Recycling in this article:

Applying Theory to Practice

I opened the ViewDiscoveryComposition Quickstart from the latest Prism-v2 Drop and modified the Employee Service class' (located in the Employees Module) implementation for the following one and ran the application:

public class EmployeeService : IEmployeeService
    {
        public ObservableCollection<BusinessEntities.Employee> RetrieveEmployees()
        {
            ObservableCollection<BusinessEntities.Employee> employees =
                new ObservableCollection<BusinessEntities.Employee>();
            for (int i = 1; i < 40001; i++)
            {
                employees.Add(new BusinessEntities.Employee(i)
                { FirstName = "John" + i,
                    LastName = "Smith", Phone = "+1 (425) 555-0101",
                    Email = "john.smith@example.com", Address = "One Microsoft Way",
                    City = "Redmond", State = "WA" });
            }

            return employees;
        }
    }

In fact, the list of employees took ages to load. I got a little deeper and found in the article mentioned above that even if the ListView performs UI Virtualization by default there are some possible reasons why UI Virtualization could be accidentally disabled. One of them was that the list was unable to scroll through its content.

Once I checked the EmployeeListView.xaml file,  I realized that it had no specified height nor implicitly showed a vertical scroll bar. The following modification in the ListView declaration was the one that made the trick:

<ListView x:Name="EmployeesList" ItemsSource="{Binding}"
SelectionChanged="EmployeesListView_SelectionChanged"
Height="250" ScrollViewer.VerticalScrollBarVisibility="Visible">

I run the application again and it took no more than one second to load the list view.

I hope you can find some good use for this. Let me know if you do.