With the raising popularity of WinRT and WP8 the demand for building complex UIs for managed apps increased significantly . A heavy UI which if not handled properly can lead to poor user experience.
This post will analyze the performance penalties of adding lots of visuals to a ListBox, present the traps of the “easy way” and suggest an alternative for overcoming them.
The problem
Take the following code which creates a collection of items and acts as a ItemsSource to an ListBox. The ListBox renders its items as Rectangles:
private void CreateRectangleItems() { var collection = new ObservableCollection(); Random random = new Random(); for (int i = 0; i < 1000; i++) { collection.Add(new Item() { X = random.Next() % (int)this.ActualWidth, Y = random.Next() % (int)this.ActualHeight }); } this.DataContext = collection; } class Item { public int X { get; set; } public int Y { get; set; } }
The solution
private void CreateGeometryItems() { var collection = new ObservableCollection(); var random = new Random(); var item = new GeometryItem(); var group = new GeometryGroup() { FillRule = FillRule.Nonzero }; item.Shape = group; for (int i = 0; i < 9000; i++) { group.Children.Add(new RectangleGeometry() { Rect = new Rect(random.Next() % (int)this.ActualWidth, random.Next() % (int)this.ActualHeight, 10, 10) }); } collection.Add(item); this.DataContext = collection; }
After seeing such massive improvements I got curios to see how this technique would work for other platforms like Windows Phone 8 and WPF.
For WP8, the results are pretty much similar, the geometry approach is couple of times faster and less memory expensive than the visuals approach.
Surprisingly, on WPF the visuals approach is not as memory expensive as is on WinRT or WP. However, the geometry approach is still twice as fast and memory efficient.
Bottom line: if you want to display and manipulate 1000+ visual elements in a ListBox consider the geometry alternative presented above, especially when using WP8 or WinRT.
One more thing 🙂
I found this technique while I was working on my Win8 app Puzzle Frenzy.
The app is available in Windows Store, check it out and tell me what you think: http://apps.microsoft.com/windows/en-GB/app/puzzle-frenzy/28238e98-ac0f-4a6b-81ea-a31a24a15acf.
You can also give your feedback on app’s review page or on app’s Facebook page http://www.facebook.com/PuzzleFrenzyApp.
Happy coding!

Great trick! Nice to know we can workaround the issue using this technique