0

WinPhone 7.1

In a ScrollViewer I have a stack panel with about 500 strings. I want to scroll the stack panel from code to a certain offset. I tried this:

for (int i = 0; i < 500; i++)
{
  tb = new TextBlock();
  tb.Text = "String #" + i.ToString();                
  this.stackPanel1.Children.Add(tb);
}
this.scrollViewer1.ScrollToVerticalOffset(200);// scroll to offset 200
this.scrollViewer1.UpdateLayout();

but it wont scroll at all.

What am I doing wrong?

Thanks

donescamillo

user1523271
  • 1,005
  • 2
  • 13
  • 27

1 Answers1

5

This will solve your problem:

Dispatcher.BeginInvoke(() =>
    {
        scrollViewer1.UpdateLayout();
        scrollViewer1.ScrollToVerticalOffset(200);
    }
);
LittleBobbyTables - Au Revoir
  • 32,008
  • 25
  • 109
  • 114
  • Hi, it works perfectly. However, can you explain why it is necessary use Dispatcher.BeginInvoke in this case? Thank you. – Jakub Krampl Jul 30 '14 at 08:18
  • Dispatcher.BeginInvoke is used for doing some work on UI thread. so "ScrollToVerticalOffset" need to be executed in UI thread to reflect change in UI. – Prateek Jaiswal Jul 30 '14 at 10:13