简体   繁体   中英

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!

Use ScrollIntoView function either by SelectedIndex or SelectedItem property.

lsbReadingChapter.ScrollIntoView(lsbReadingChapter.SelectedIndex);

or

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

采用

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

终于解决了,方法是在Lisbox的父级网格加载中调用lsbReadingChapter.ScrollIntoView。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM