后退按钮从收藏夹跳过第一项

时间:2017-09-21 06:37:45

标签: c# uwp listboxitem

我有两个按钮,一个是向后,另一个是向前。 两个按钮都会逐个显示文本块中的“收藏”项。 前进按钮正常工作,但后退按钮始终跳过收藏列表中的第一项。

  

示例 - 我在收藏夹列表中有5个项目。如果我在第二项,   如果我按向后按钮然后它直接跳转到最后一项并跳过   收藏列表中的第一项

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;
    }
}

2 个答案:

答案 0 :(得分:2)

在检查到达列表的开头时,请换取position <= 0。这包括第一项的情况,其中position == 0

将条件更改为position < 0,它将按预期工作。

答案 1 :(得分:2)

如果是条件,你需要更新你,它应该是 _displayedFavoriteIndex&lt; 0 而不是 _displayedFavoriteIndex&lt; = 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;
    }
}