Tuesday, September 06, 2011

Faster WPF ComboBoxes

If you create a WPF ComboBox with 2000 items it will take about 2 seconds to drop down, and about 1 second to retract back. But you can make all operations complete instantly if the items are simple (such as strings). If you are writing XAML, add:


<ComboBox>
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel />
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>

...
</ComboBox>


If you are writing C#, add:


comboBox.ItemsPanel = new ItemsPanelTemplate(new FrameworkElementFactory(typeof(VirtualizingStackPanel)));


Thanks to Henry Hahn for the XAML code I started from. Reading the C# version, I am reminded of the Hammer Factory joke.

2 comments:

Pradeep said...

Hi Neil, why waste time on XAML.. when you can create HTML5/JS apps? HTML5/JS are going to be supported for creating native apps in win8

Neil Mitchell said...

Pradeep: WPF works, is a lot more feature rich than HTML5/JS, and sidesteps lots of the security issues you get in JS, and is ready now. I don't like programming in XAML, but it does give very nice end user experiences.

But don't take this as a recommendation to use XAML, merely some help if you are forced to use it. At some point I'll write a proper blog article on my opinion of XAML.