0

我的 Windows Phone 应用程序中有一个ListBox、一个 ShowButton和一个TextBlock

每当用户单击 Show时,  应在 中显示Button一个项目。如果用户再次单击 Show ,则应显示下一个项目。ListBoxTextBlockButton

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)
     {
          // ??????
     }
}

怎样才能实现这样的功能?

4

1 回答 1

1

这可以很容易地直接使用索引。

假设您用于ListBox项目的列表称为listobj,那么您可以使用以下内容:

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

请注意,您不必检查是否FavoriteListBoxis null,因为这种情况永远不会发生 - 所有控件都使用InitializeComponent构造函数中的调用进行初始化。

于 2017-01-06T05:44:25.543 回答