'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 1:[1]
Use ScrollIntoView function either by SelectedIndex or SelectedItem property.
lsbReadingChapter.ScrollIntoView(lsbReadingChapter.SelectedIndex);
or
lsbReadingChapter.ScrollIntoView(lsbReadingChapter.SelectedItem);
Solution 2:[2]
Use
lsbReadingChapter.ScrollIntoView(lsbReadingChapter.Items[lsbReadingChapter.SelectedIndex]);
Solution 3:[3]
public static void ScrollToSelectedItem(ListBox control)
{
if (control.SelectedIndex != -1)
control.TopIndex = control.SelectedIndex;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Muhammad Umar |
| Solution 2 | |
| Solution 3 | ????? ??? ????? |
