Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you access the ScrollViewer element of a ListBox control in Silverlight/C#?

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

like image 625
Yttrium Avatar asked Nov 04 '08 21:11

Yttrium


2 Answers

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.

like image 69
Dan Avatar answered Oct 16 '22 10:10

Dan


Good question. I didn't find a way to do it directly, but came fairly close by looking at the Silverlight Controls project (they use the scrollviewer on the items control in some of the classes). Here is how you can get it, but it requires a custom listbox:

public class TestBox : ListBox
{
    private ScrollViewer _scrollHost;

    protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
    {
        var itemsHost = VisualTreeHelper.GetParent(element) as Panel;

        for (DependencyObject obj = itemsHost; obj != item && obj != null; obj = VisualTreeHelper.GetParent(obj))
        {
            ScrollViewer viewer = obj as ScrollViewer;
            if (viewer != null)
            {
                _scrollHost = viewer;
                break;
            }
         }

        base.PrepareContainerForItemOverride(element, item);
    }
}

There might be another way to hook into that event (or another way to get that panel), If you look at the template for the ListBox you will see the scroll viewer is actually named "ScrollViewer", however the GetTemplateChild method is protected so you would still need to create a custom class.

like image 20
Bryant Avatar answered Oct 16 '22 12:10

Bryant