views:

3234

answers:

4

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

+1  A: 

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.

Bryant
+3  A: 

For anyone else...

Best way is to do this:

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

burnt_hand
A: 
ScrollViewer scrollViewer = yourListBox.getScrollHost();

Is null if no datasourse set to the listbox, in my case it return properly UI Element only after below code executed

myListBox.ItemsSource = list;
Sedgar
A: 

You can call :

myListBox.ApplyTemplate();

to force the ListBox visual tree to be created, otherwise GetTemplateChild() will return Null if you attempt to access it immediatly.

This works well combined with "Erno de Weerd" explanation : inherit ListBox to be able to call GetTemplateChild() method.

I also tried :

  • to use ListBox extension method "GetScrollHost()" but it never worked for me (even after full page initialisations).
  • "FindName()", but it didn't work, even when i specified the ScrollViewer name into the ListBox Template.

Emmanuel (Silverlight 3)

E.Létondor