Pages

Friday, June 11, 2010

Smooth Pixel Scrolling in WPF ListView / ListBox

WPF comes with lots of fun and advantages. We can change the look and behavior of a control very easily which would have been very cumbersome when we are in normal winforms applications. WPF has few flexibilities like Superior Binding capabilities, Animation, Transformation, Virtualizations etc. Each of these made the framework richer in all respect.

In WPF, ListBox and ListView scrolls based on the items. The Scrolling on those controls are not smooth as the ScrollBar doesnt animate the scroller as we do with other controls. Sometimes you will also see the scroller is produced with incorrect size. I mean to say, the same scroller when it is in the top, the size is different than when its in the bottom. This happens basically because of Virtualization implemented on those controls.

ListBox and ListView actually has VirtualizingStackPanel enabled by default. This means, WPF will not actually create all the items and hence determine the scrollbar, rather the size of the ScrollBar is calculated based on the average multiple of items in its display with the number of items actually there in the CollectionView.  Thus if you have items which are in display bigger than which are not in view, you will see the size of the ScrollBar increased abruptly whenever you scroll down a bit.


You can see in the above snap, the irregular sized items will make the scrollbar to behave strange.

The easiest fix to this issue is you set
ScrollViewer.CanContentScroll = false

This will make the scrollviewer to disable the scrolling and hence the ListBox scroller appear.
The main problem with this approach is that, if you Disable the ContentScroll property of the ScrollViewer, it means it will completely stop Virtualizing. And hence if you have a big dataItems, it will cause huge performance issue.

You can also create your own scroolViewer using IScrollInfo. You have to create your custom panel to implement your scroller. This will be best.
I am also thinking to build one panel which might use Virtualizing as well. I will give you the idea when I finish.

For time being you can use CanContentScroll = false.

Thank you for reading.

No comments:

Post a Comment

Please make sure that the question you ask is somehow related to the post you choose. Otherwise you post your general question in Forum section.