Search code examples
c#windows-phone-8

How to Scroll into selected item in listbox


I am really confused with wp8 listbox scrolling. with below simple code I am scrolling to the selected index (item), but it doesn't work.

lsbReadingChapter.SelectionChanged -= lsbReadingChapter_SelectionChanged;
            _lastAyaSelectedIndex = startingAya;
            lsbReadingChapter.ItemsSource = null;
            lsbReadingChapter.ItemsSource = ds.getArabicTextWithTranslation(currentChapter);
            lsbReadingChapter.SelectedIndex = startingAya;
            lsbReadingChapter.UpdateLayout();
            lsbReadingChapter.ScrollIntoView(lsbReadingChapter.SelectedItem);
            lsbReadingChapter.SelectionChanged += lsbReadingChapter_SelectionChanged;

the selectedIndex is always greater than zero, but the listbox show the 1st item in the list and doesn't scroll.

Here is my xaml

ListBox x:Name="lsbReadingChapter" HorizontalAlignment="Stretch" Grid.Row="1" ScrollViewer.VerticalScrollBarVisibility="Visible" Width="480" SelectionChanged="lsbReadingChapter_SelectionChanged" Loaded="lsbReadingChapter_Loaded">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel HorizontalAlignment="Stretch" Width="480" Orientation="Vertical" Background="{Binding Converter={StaticResource AlternateRowConverter}}" >
                        <TextBlock Foreground="Black" Padding="20,0,30,0" TextWrapping="Wrap" HorizontalAlignment="{Binding HAlignment}" FontSize="{Binding ArabicFontSize}">
                            <Run Text="{Binding Aya}"/>
                            <Run Text="{Binding AyaID, StringFormat=﴿\{0\}﴾}" Foreground="Blue" FontSize="30"/>
                        </TextBlock>
                        <TextBlock Padding="20,0,30,0" Text="{Binding AyaTranslation}" Foreground="Black" FontSize="{Binding TranslationFontSize}" TextWrapping="Wrap" HorizontalAlignment="{Binding HAlignment}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

I don't know why it doesn't scroll to the selected index?

Thanks!


Solution

  • finally solved, by calling lsbReadingChapter.ScrollIntoView in grid load parent of Lisbox.