0

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?

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91
Shubham Sahu
  • 1,963
  • 1
  • 17
  • 34
  • hey! there is one answer which is not visible now, but not work int currentListIndex = 0; if (FavoriteListBox.Items.Count <= currentListIndex) { DisplayTextBlock.Text = FavoriteListBox.Items[currentListIndex++].ToString(); } else { currentListIndex = 0; DisplayTextBlock.Text = FavoriteListBox.Items[0].ToString(); } – Shubham Sahu Jan 06 '17 at 05:34

1 Answers1

1

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.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91