DEV Community

Cover image for Making a WPF Expander Faster with UI Reuse and Virtualization
Rishabh
Rishabh

Posted on

Making a WPF Expander Faster with UI Reuse and Virtualization

Working with large collections in WPF can introduce performance issues that aren't always obvious at first.

Recently, I worked on optimizing an Expander in our application that contained around 1,000 sequences. Opening it was noticeably slow, so I started investigating what was happening behind the scenes.

The Problem

We had an Expander that displayed approximately 1,000 sequences.

Each sequence also had a three-dot (⋮) button that provided additional actions.

The problem was in how the UI was structured.

In the existing XAML implementation, a separate three-dot button was created for every sequence item.

This meant WPF had to create and manage a large number of additional UI elements when loading the collection.

With around 1,000 sequences, this introduced unnecessary UI creation overhead and affected the Expander's opening performance.

Finding the Bottleneck

I started examining the XAML structure and how the sequence items were being rendered.

I found that the three-dot button was being repeatedly created for individual items, even though its functionality and structure were reusable.

This was unnecessary work that could be optimized.

The Solution

I approached the problem in two ways:

  1. Reusing the Button

Instead of repeatedly creating the same button structure, I changed the implementation to reuse the button reference and avoid unnecessary repeated creation.

  1. Implementing UI Virtualization

I also implemented virtualization so that WPF would create UI elements only for the items needed for the visible portion of the collection rather than creating everything upfront.

This reduced the number of UI elements that needed to be generated and managed at once.

The Result

The Expander now opens significantly faster, even with approximately 1,000 sequences.

The improvement came from reducing unnecessary UI element creation and using virtualization to manage a large collection more efficiently.

What I Learned

This was another reminder that UI performance is not just about how much data an application handles.

It's also about how efficiently the UI framework creates, manages, and renders that data.

When working with large collections in WPF, consider:

  • Avoiding unnecessary UI element creation.
  • Reusing common UI definitions and resources.
  • Implementing UI virtualization.
  • Investigating DataTemplates and visual tree complexity.
  • Understanding when UI elements are actually created and rendered.

Sometimes, optimizing the UI structure can make a bigger difference than optimizing the underlying data operations.

Top comments (0)