Search code examples
c#uwplistboxitem

Backward Button Skip First Item from favorites


I have two buttons one is backward and other is forward. Both Button show Favorited item in a text block one by one. Forward button works correctly but Backward button always skip first item from the favorite list.

Example - I have 5 items in a favorite list. If i am in second item, if i press backward button then it directly jump to last item and skip first item from favorite list

XAML

 <Button Name="BackwardButton" FontFamily="Segoe MDL2 Assets" Content="&#xE26C;" />
 <Button Name="ForwardButton" FontFamily="Segoe MDL2 Assets" Content="&#xE26B;" />
 <TextBlock Name="DisplayTextBlock" />

C#

private int _displayedFavoriteIndex = -1;

private void BackwardButton_Tapped(object sender, TappedRoutedEventArgs e)
{
    if (FavoriteListBox.Items.Count > 1)
    {
        //move to the previous item
        _displayedFavoriteIndex--;
        if (_displayedFavoriteIndex <= 0)
        {
            //we have reached the end of the list
            _displayedFavoriteIndex = listobj.Count - 1;
        }
        //show the item            
        DisplayTextBlock.Text = listobj[ _displayedFavoriteIndex ].AnswerName;
    }
}

private void ForwardButton_Tapped(object sender, TappedRoutedEventArgs e)
{
    if (FavoriteListBox.Items.Count > 1)
    {
        //move to the next item
        _displayedFavoriteIndex++;
        if (_displayedFavoriteIndex >= listobj.Count)
        {
            //we have reached the end of the list
            _displayedFavoriteIndex = 0;
        }
        //show the item            
        DisplayTextBlock.Text = listobj[ _displayedFavoriteIndex ].AnswerName;
    }
}

Solution

  • You need to update you if condition, it should be _displayedFavoriteIndex < 0 instead of _displayedFavoriteIndex <= 0

    private void BackwardButton_Tapped(object sender, TappedRoutedEventArgs e)
    {
        if (FavoriteListBox.Items.Count > 1)
        {
            //move to the previous item
            _displayedFavoriteIndex--;
            if (_displayedFavoriteIndex < 0) // Change here
            {
                //we have reached the end of the list
                _displayedFavoriteIndex = listobj.Count - 1;
            }
            //show the item            
            DisplayTextBlock.Text = listobj[ _displayedFavoriteIndex ].AnswerName;
        }
    }