views:

59

answers:

2

I'm developing a silverlight 4 application and I often use Listboxes and databinding. What I would like to do is set the scrollbar position to the bottom of my Listbox. Is there a simple way to do this?

By the way I've tried this but it doesn't work:

COTO_dg.ScrollIntoView(COTO_dg.Items[COTO_dg.Items.Count - 1]);

Thank You, Ephismen.

+2  A: 

The code you posted works fine, but not right after the items are inserted into the ItemsControl. To make sure you give the control enough time to update itself, it's easier to use:

Dispatcher.BeginInvoke(() => lb.ScrollIntoView(lb.Items.Last());

where lb is a ListBox or any other ItemsControl. (this works in the constructor of a Silverlight page, right after some code adding a bunch of items, just tested).

Note: the references were the default ones inserted by Visual Studio:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
Alex Paven
I don't know how you tested this because it gives me an error:
Ephismen
It says I am missing a assembly reference in using System.Windows.Controls for 'Last' and that there is a problem with lambda expression: "Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type"
Ephismen
I created a new silverlight 4 project and only wrote that code. I've edited the answer with the default references inserted by Visual Studio.
Alex Paven
A: 

Alright, found something not very clean but it works. I'll post it so other people see how I did it:

Here is how I invoke the method:

Dispatcher.BeginInvoke(new lol(my_method));

I created an anonymous delegate and the corresponding method that I will call into it:

    public delegate void lol();

    public my_method()
    {
        COTO_dg.ScrollIntoView(COTO_dg.Items[COTO_dg.Items.Count - 1]);
    }

Hope this helps someone.

Ephismen
You can also make it 'cleaner' by invoking an Action instead of creating a delegate: `Dispatcher.BeginInvoke(new Action(my_method))` or `Dispatcher.BeginInvoke(new Action(() => my_method()))` or the line used in my original answer. That inline lambda expression should be automatically converter to an Action.
Alex Paven
Thanks I'll try that. I'm quite new to delegates and lambda expressions, so still having some small interpretation problems. But practice makes it perfect !
Ephismen