Search code examples
c#listboxwindows-phone-8.1windows-phone-silverlight

Show ListBox Items One By One (Windows Phone)


I have a ListBox, a Show Button, and a TextBlock in my Windows Phone application.

Whenever the user clicks on the Show Button, an item from the ListBox  should be shown in TextBlock. If the user clicks on Show Button again, the next item should be shown.

XAML

<ListBox x:Name="FavoriteListBox"  
         SelectionChanged="FavoriteListBox_SelectionChanged"                         
         ItemContainerStyle="{StaticResource CustomListBoxItemStyle}"
         Height="300" Width="250">
    <ListBox.ItemTemplate>
         <DataTemplate>
             <TextBlock x:Name="FavoriteListBoxTextBlock" 
                        FontSize="40" FontWeight="SemiBold"
                        Text="{Binding AnswerName}"/>
         </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

<TextBlock x:Name="DisplayTextBlock"/>

<Button x:Name="ShowButton" Click="ShowButton_Click"/>

C#

private void ShowButton_Click(object sender, EventArgs e)
{
    if(FavoriteListBox != null)
     {
          // ??????
     }
}

How can achieve such functionality?


Solution

  • This can be quite easily using indices directly.

    Suppose the list you use for the ListBox items is called listobj, then you can use the following:

    private int _displayedFavoriteIndex = -1;
    
    private void ShowButton_Click(object sender, EventArgs e)
    {
        //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;
    }
    

    Note you don't have to check whether FavoriteListBox is null, because such situation will never happen - all controls are initialized with the InitializeComponent call in the constructor.