ARH
ARH

Reputation: 1716

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!

Upvotes: 0

Views: 7600

Answers (4)

public static void ScrollToSelectedItem(ListBox control)
{
    if (control.SelectedIndex != -1)
        control.TopIndex = control.SelectedIndex;
}

Upvotes: 1

ARH
ARH

Reputation: 1716

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

Upvotes: -2

Nitin Varpe
Nitin Varpe

Reputation: 10694

Use

 lsbReadingChapter.ScrollIntoView(lsbReadingChapter.Items[lsbReadingChapter.SelectedIndex]);

Upvotes: 0

Muhammad Umar
Muhammad Umar

Reputation: 3781

Use ScrollIntoView function either by SelectedIndex or SelectedItem property.

lsbReadingChapter.ScrollIntoView(lsbReadingChapter.SelectedIndex);

or

lsbReadingChapter.ScrollIntoView(lsbReadingChapter.SelectedItem);

Upvotes: 3

Related Questions