C# – How to access the ScrollViewer element of a ListBox control in Silverlight/C#

clistboxsilverlight

I wish to dynamically change the scroll position of a Silverlight ListBox from C#, and I need to know how to access the ScrollViewer element of a ListBox control from C#?

Thanks guys,
Jeff

Best Answer

From within a class that inherits from the ListBox class, you can use the Protected GetTemplateChild():

var myScrollviewer = myListBox.GetTemplateChild("ScrollViewer") as ScrollViewer;

If you want to access this from outside the ListBox, then exposing the ScrollViewer via a Property should work, again through inheritance.

CAVEAT: If you have set your own custom template, then this Scrollviewer may not exist. You can use the templates Scrollviewer name instead of the "ScrollViewer" in the method above.